commit e9e3a0bf0d027205e1476dc8369b754cb0f0a5bd Author: sigonasr2 Date: Fri Sep 25 18:17:29 2020 +0900 Create DivaBotGuardian to monitor stream input. diff --git a/DivaBotGuardian/.gitignore b/DivaBotGuardian/.gitignore new file mode 100644 index 0000000..3eaf567 --- /dev/null +++ b/DivaBotGuardian/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.classpath +/.project diff --git a/DivaBotGuardian/.settings/org.eclipse.jdt.core.prefs b/DivaBotGuardian/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/DivaBotGuardian/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/DivaBotGuardian/src/sig/Guardian.java b/DivaBotGuardian/src/sig/Guardian.java new file mode 100644 index 0000000..3be3bbb --- /dev/null +++ b/DivaBotGuardian/src/sig/Guardian.java @@ -0,0 +1,47 @@ +package sig; +import java.io.File; +import java.io.IOException; + +import sig.utils.FileUtils; + +public class Guardian { + public static int USERID = -1; + public static long streamLastModified = -1; + public static STAGE currentStage = STAGE.STARTING; + + enum STAGE{ + STARTING, + RUNNING, + CLEANUP; + } + + public static void main(String[] args) throws InterruptedException, IOException { + File f = new File("streams","output"+USERID+".png"); + File tempf = new File("streams","tempoutput"+USERID+".png"); + switch (currentStage) { + case STARTING:{ + USERID = Integer.parseInt(args[0]); + while (currentStage==STAGE.STARTING) { + if (f.exists()) { + streamLastModified = f.lastModified(); + currentStage=STAGE.RUNNING; + } + Thread.sleep(100); + } + }break; + case RUNNING:{ + while (currentStage==STAGE.RUNNING) { + FileUtils.copyFile(f, tempf); + if (System.currentTimeMillis()>=streamLastModified+5000) { + currentStage=STAGE.CLEANUP; + System.out.println("Stream is no longer being updated! Shutting down!"); + } + Thread.sleep(100); + } + }break; + case CLEANUP:{ + f.delete(); + }break; + } + } +} diff --git a/DivaBotGuardian/src/sig/utils/Audio.java b/DivaBotGuardian/src/sig/utils/Audio.java new file mode 100644 index 0000000..8e7006c --- /dev/null +++ b/DivaBotGuardian/src/sig/utils/Audio.java @@ -0,0 +1,219 @@ +package sig.utils; +import java.util.ArrayList; +import java.util.List; + +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.BooleanControl; +import javax.sound.sampled.CompoundControl; +import javax.sound.sampled.Control; +import javax.sound.sampled.Control.Type; +import javax.sound.sampled.FloatControl; +import javax.sound.sampled.Line; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.Mixer; +import javax.sound.sampled.Mixer.Info; + +public class Audio { + + public static void main(String[] args) throws Exception { + System.out.println(getHierarchyInfo()); + System.out.println(getMasterOutputVolume()); + } + + public static void setMasterOutputVolume(float value) { + if (value < 0 || value > 1) + throw new IllegalArgumentException( + "Volume can only be set to a value from 0 to 1. Given value is illegal: " + value); + Line line = getMasterOutputLine(); + if (line == null) throw new RuntimeException("Master output port not found"); + boolean opened = open(line); + try { + FloatControl control = getVolumeControl(line); + if (control == null) + throw new RuntimeException("Volume control not found in master port: " + toString(line)); + control.setValue(value); + } finally { + if (opened) line.close(); + } + } + + public static Float getMasterOutputVolume() { + Line line = getMasterOutputLine(); + if (line == null) return null; + boolean opened = open(line); + try { + FloatControl control = getVolumeControl(line); + if (control == null) return null; + return control.getValue(); + } finally { + if (opened) line.close(); + } + } + + public static void setMasterOutputMute(boolean value) { + Line line = getMasterOutputLine(); + if (line == null) throw new RuntimeException("Master output port not found"); + boolean opened = open(line); + try { + BooleanControl control = getMuteControl(line); + if (control == null) + throw new RuntimeException("Mute control not found in master port: " + toString(line)); + control.setValue(value); + } finally { + if (opened) line.close(); + } + } + + public static Boolean getMasterOutputMute() { + Line line = getMasterOutputLine(); + if (line == null) return null; + boolean opened = open(line); + try { + BooleanControl control = getMuteControl(line); + if (control == null) return null; + return control.getValue(); + } finally { + if (opened) line.close(); + } + } + + public static Line getMasterOutputLine() { + for (Mixer mixer : getMixers()) { + for (Line line : getAvailableOutputLines(mixer)) { + if (line.getLineInfo().toString().contains("Master")) return line; + } + } + return null; + } + + public static FloatControl getVolumeControl(Line line) { + if (!line.isOpen()) throw new RuntimeException("Line is closed: " + toString(line)); + return (FloatControl) findControl(FloatControl.Type.VOLUME, line.getControls()); + } + + public static BooleanControl getMuteControl(Line line) { + if (!line.isOpen()) throw new RuntimeException("Line is closed: " + toString(line)); + return (BooleanControl) findControl(BooleanControl.Type.MUTE, line.getControls()); + } + + private static Control findControl(Type type, Control... controls) { + if (controls == null || controls.length == 0) return null; + for (Control control : controls) { + if (control.getType().equals(type)) return control; + if (control instanceof CompoundControl) { + CompoundControl compoundControl = (CompoundControl) control; + Control member = findControl(type, compoundControl.getMemberControls()); + if (member != null) return member; + } + } + return null; + } + + public static List getMixers() { + Info[] infos = AudioSystem.getMixerInfo(); + List mixers = new ArrayList(infos.length); + for (Info info : infos) { + Mixer mixer = AudioSystem.getMixer(info); + mixers.add(mixer); + } + return mixers; + } + + public static List getAvailableOutputLines(Mixer mixer) { + return getAvailableLines(mixer, mixer.getTargetLineInfo()); + } + + public static List getAvailableInputLines(Mixer mixer) { + return getAvailableLines(mixer, mixer.getSourceLineInfo()); + } + + private static List getAvailableLines(Mixer mixer, Line.Info[] lineInfos) { + List lines = new ArrayList(lineInfos.length); + for (Line.Info lineInfo : lineInfos) { + Line line; + line = getLineIfAvailable(mixer, lineInfo); + if (line != null) lines.add(line); + } + return lines; + } + + public static Line getLineIfAvailable(Mixer mixer, Line.Info lineInfo) { + try { + return mixer.getLine(lineInfo); + } catch (LineUnavailableException ex) { + return null; + } + } + + public static String getHierarchyInfo() { + StringBuilder sb = new StringBuilder(); + for (Mixer mixer : getMixers()) { + sb.append("Mixer: ").append(toString(mixer)).append("\n"); + + for (Line line : getAvailableOutputLines(mixer)) { + sb.append(" OUT: ").append(toString(line)).append("\n"); + boolean opened = open(line); + for (Control control : line.getControls()) { + sb.append(" Control: ").append(toString(control)).append("\n"); + if (control instanceof CompoundControl) { + CompoundControl compoundControl = (CompoundControl) control; + for (Control subControl : compoundControl.getMemberControls()) { + sb.append(" Sub-Control: ").append(toString(subControl)).append("\n"); + } + } + } + if (opened) line.close(); + } + + for (Line line : getAvailableOutputLines(mixer)) { + sb.append(" IN: ").append(toString(line)).append("\n"); + boolean opened = open(line); + for (Control control : line.getControls()) { + sb.append(" Control: ").append(toString(control)).append("\n"); + if (control instanceof CompoundControl) { + CompoundControl compoundControl = (CompoundControl) control; + for (Control subControl : compoundControl.getMemberControls()) { + sb.append(" Sub-Control: ").append(toString(subControl)).append("\n"); + } + } + } + if (opened) line.close(); + } + + sb.append("\n"); + } + return sb.toString(); + } + + public static boolean open(Line line) { + if (line.isOpen()) return false; + try { + line.open(); + } catch (LineUnavailableException ex) { + return false; + } + return true; + } + + public static String toString(Control control) { + if (control == null) return null; + return control.toString() + " (" + control.getType().toString() + ")"; + } + + public static String toString(Line line) { + if (line == null) return null; + Line.Info info = line.getLineInfo(); + return info.toString();// + " (" + line.getClass().getSimpleName() + ")"; + } + + public static String toString(Mixer mixer) { + if (mixer == null) return null; + StringBuilder sb = new StringBuilder(); + Info info = mixer.getMixerInfo(); + sb.append(info.getName()); + sb.append(" (").append(info.getDescription()).append(")"); + sb.append(mixer.isOpen() ? " [open]" : " [closed]"); + return sb.toString(); + } + +} \ No newline at end of file diff --git a/DivaBotGuardian/src/sig/utils/DebugUtils.java b/DivaBotGuardian/src/sig/utils/DebugUtils.java new file mode 100644 index 0000000..f318564 --- /dev/null +++ b/DivaBotGuardian/src/sig/utils/DebugUtils.java @@ -0,0 +1,17 @@ +package sig.utils; + + +public class DebugUtils { + public static void showStackTrace() { + System.out.println("Trace:"+getStackTrace()); + } + + public static String getStackTrace() { + StackTraceElement[] stacktrace = new Throwable().getStackTrace(); + StringBuilder stack = new StringBuilder("Mini stack tracer:"); + for (int i=0;i0) { + AttributedString as = new AttributedString(message); + as.addAttribute(TextAttribute.FONT, font); + as.addAttribute(TextAttribute.KERNING,TextAttribute.KERNING_ON); + as.addAttribute(TextAttribute.WIDTH,TextAttribute.WIDTH_EXTENDED); + as.addAttribute(TextAttribute.TRACKING,0.5); + g.setColor(shadow_color); + Graphics2D g2 = (Graphics2D) g; + FontRenderContext frc = g2.getFontMetrics(font).getFontRenderContext(); + GlyphVector gv = font.createGlyphVector(frc, message); + Shape shape = gv.getOutline((int)(x+xoffset),(int)(y+yoffset)); + g2.setClip(null); + g2.setStroke(new BasicStroke(font_thickness + outline_thickness*2)); + g2.setColor(shadow_color); + g2.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.draw(shape); + GlyphVector gv2 = font.createGlyphVector(frc, message); + Shape shape2 = gv2.getOutline((int)(x+xoffset),(int)(y+yoffset)); + g2.setClip(null); + g2.setStroke(new BasicStroke(font_thickness)); + g2.setColor(text_color); + g2.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.draw(shape2); + g2.setColor(text_color); + g2.drawString(as.getIterator(),(int)(x+xoffset),(int)(y+yoffset)); + } + } + public static void drawCenteredOutlineText(Graphics g, Font font, double x, double y, int font_size, int outline_size, Color text_color, Color shadow_color, String message) { + Rectangle2D textBounds = TextUtils.calculateStringBoundsFont(message, font); + drawOutlineText(g,font,x,y,-textBounds.getWidth()/2,-textBounds.getHeight()/2,font_size,outline_size,text_color,shadow_color,message); + } + public static void drawCenteredOutlineText(Graphics g, Font font, double x, double y, int outline_size, Color text_color, Color shadow_color, String message) { + drawCenteredOutlineText(g,font,x,y,1,outline_size,text_color,shadow_color,message); + } + public static void drawText(Graphics g, double x, double y, Color color, String message) { + if (message.length()>0) { + AttributedString as = new AttributedString(message); + as.addAttribute(TextAttribute.FONT, MyPanel.programFont); + g.setColor(color); + g.drawString(as.getIterator(),(int)x,(int)y); + } + } + public static void drawTextFont(Graphics g, Font font, double x, double y, Color color, String message) { + if (message.length()>0) { + AttributedString as = new AttributedString(message); + as.addAttribute(TextAttribute.FONT, font); + g.setColor(color); + g.drawString(as.getIterator(),(int)x,(int)y); + } + } + public static void drawHealthbar(Graphics g, Rectangle bounds, double pct, Color healthbarcol) { + g.setColor(Color.BLACK); + g.draw3DRect((int)bounds.getX(), (int)bounds.getY(), (int)bounds.getWidth(), (int)bounds.getHeight(), true); + g.setColor(healthbarcol); + g.fill3DRect((int)bounds.getX()+1, (int)bounds.getY()+1, (int)(bounds.getWidth()*pct)-1, (int)bounds.getHeight()-1, true); + } + /** + * Centers the text along the X Axis. + */ + public static void drawCenteredText(Graphics g, Font font, int x, int y, Color color, String text) { + AttributedString as = new AttributedString(text); + as.addAttribute(TextAttribute.FONT, font); + g.setColor(color); + Rectangle2D textBounds = TextUtils.calculateStringBoundsFont(text, font); + g.drawString(as.getIterator(),(int)(x-textBounds.getWidth()/2),(int)(y+textBounds.getHeight())); + } + + public static Color convertStringToColor(String s) { + String[] split = s.split(","); + if (split.length==3) { + return new Color( + Math.min(Math.abs(Integer.parseInt(split[0])),255), + Math.min(Math.abs(Integer.parseInt(split[1])),255), + Math.min(Math.abs(Integer.parseInt(split[2])),255)); + } else + if (split.length==4) { + return new Color( + Math.min(Math.abs(Integer.parseInt(split[0])),255), + Math.min(Math.abs(Integer.parseInt(split[1])),255), + Math.min(Math.abs(Integer.parseInt(split[2])),255), + Math.min(Math.abs(Integer.parseInt(split[3])),255)); + } else { + System.out.println("WARNING! Invalid Color string specified ("+s+")."); + return null; + } + } + + public static void drawImage(Graphics g, Image img, double x, double y, Color blend_col, ImageObserver source) { + BufferedImage tmp = new BufferedImage(img.getWidth(source),img.getHeight(source),BufferedImage.TYPE_INT_ARGB); + Graphics2D g2 = tmp.createGraphics(); + g2.drawImage(img, 0, 0, null); + g2.setComposite(AlphaComposite.SrcAtop); + g2.setColor(blend_col); + g2.fillRect(0, 0, img.getWidth(source), img.getHeight(source)); + g2.dispose(); + g.drawImage(tmp,(int)x,(int)y,source); + } + + public static void drawImageScaled(Graphics g, Image img, double x, double y, double xsize, double ysize, Color blend_col, ImageObserver source) { + BufferedImage tmp = new BufferedImage(img.getWidth(source),img.getHeight(source),BufferedImage.TYPE_INT_ARGB); + Graphics2D g2 = tmp.createGraphics(); + g2.drawImage(img, 0, 0, null); + g2.setComposite(AlphaComposite.SrcAtop); + g2.setColor(blend_col); + g2.fillRect(0, 0, img.getWidth(source), img.getHeight(source)); + g2.dispose(); + g.drawImage(tmp,(int)x,(int)y,(int)xsize,(int)ysize,source); + } + + public static Color invertColor(Color c) { + return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue(),255); + } +} diff --git a/DivaBotGuardian/src/sig/utils/FileUtils.java b/DivaBotGuardian/src/sig/utils/FileUtils.java new file mode 100644 index 0000000..bce5562 --- /dev/null +++ b/DivaBotGuardian/src/sig/utils/FileUtils.java @@ -0,0 +1,385 @@ +package sig.utils; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.Writer; +import java.net.ConnectException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class FileUtils { + public static String[] readFromFile(String filename) throws IOException { + File file = new File(filename); + //System.out.println(file.getAbsolutePath()); + List contents= new ArrayList(); + if (file.exists()) { + FileInputStream in = new FileInputStream(file); + InputStreamReader isr = new InputStreamReader(in,Charset.forName("UTF-8")); + BufferedReader br = new BufferedReader(isr); + String readline = br.readLine(); + do { + if (readline!=null) { + //System.out.println(readline); + contents.add(readline); + readline = br.readLine(); + }} while (readline!=null); + br.close(); + isr.close(); + in.close(); + } + return contents.toArray(new String[contents.size()]); + } + + private static String readAll(Reader rd) throws IOException { + StringBuilder sb = new StringBuilder(); + int cp; + while ((cp = rd.read()) != -1) { + sb.append((char) cp); + } + return sb.toString(); + } + + private static String readFilter(Reader rd, HashMap channel_ids) throws IOException { + StringBuilder sb = new StringBuilder(); + boolean allowed=false; + boolean quotation_mark=false; + boolean endquotation_mark=false; + boolean foundChannel=false; + boolean nextBrace=false; + boolean outputStuff=false; + String numb = ""; + int braceCount=0; + int channelCount=0; + int vals=0; + int cp; + while ((cp = rd.read()) != -1) { + if (braceCount==0) { + allowed=true; + } else + if (braceCount==1 && !quotation_mark){ + quotation_mark=true; + numb=""; + allowed=false; + } else + if (!endquotation_mark) { + if ((char)cp >= '0' && + (char)cp <= '9') { + allowed=false; + numb+=(char)cp; + } else { + allowed=false; + endquotation_mark=true; + try { + if (channel_ids.containsKey(Long.parseLong(numb))) { + if (channelCount>=1) { + sb.append(","); + } + sb.append("\""+numb+"\""); + foundChannel=true; + System.out.println("Found channel "+numb); + outputStuff=true; + } + } catch (NumberFormatException e) { + + } + } + } else + if (!nextBrace && foundChannel) { + allowed=true; + if ((char)cp == '{') { + nextBrace=true; + } + } else + if (foundChannel) { + allowed=true; + if (braceCount==1) { + allowed=false; + channelCount++; + quotation_mark=false; + endquotation_mark=false; + foundChannel=false; + nextBrace=false; + } + } else { + allowed=false; + if (braceCount==1) { + allowed=false; + quotation_mark=false; + endquotation_mark=false; + foundChannel=false; + nextBrace=false; + } + } + + /*if (outputStuff && vals++<1000) { + System.out.print((char)cp); + }*/ + if ((char)cp == '{') { + braceCount++; + //System.out.println("Brace count is "+braceCount+"."); + } else + if ((char)cp == '}') { + braceCount--; + //System.out.println("Brace count is "+braceCount+"."); + } + + if (allowed) { + sb.append((char) cp); + } + } + sb.append("}"); + //System.out.println("============="); + //System.out.println(sb.toString()); + return sb.toString(); + } + + public static JSONObject readJsonFromUrlWithFilter(String url, HashMap filter) throws IOException, JSONException { + return readJsonFromUrlWithFilter(url,filter,null,false); + } + + public static JSONObject readJsonFromFileWithFilter(String file, HashMap filter) throws IOException, JSONException { + InputStream is = new FileInputStream(new File(file)); + try { + BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); + String jsonText = readFilter(rd,filter); + JSONObject json = new JSONObject(jsonText); + jsonText=null; + return json; + } finally { + is.close(); + } + } + + public static JSONObject readJsonFromUrlWithFilter(String url, HashMap filter, String file, boolean writeToFile) throws IOException, JSONException { + InputStream is = new URL(url).openStream(); + try { + BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); + String jsonText = readFilter(rd,filter); + if (writeToFile) { + writetoFile(new String[]{jsonText},file); + } + JSONObject json = new JSONObject(jsonText); + return json; + } finally { + is.close(); + } + } + + public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { + return readJsonFromUrl(url,null,false); + } + + public static JSONArray readJsonArrayFromUrl(String url) throws IOException, JSONException { + return readJsonArrayFromUrl(url,null,false); + } + + public static JSONObject readJsonFromFile(String file) throws IOException, JSONException { + InputStream is = new FileInputStream(new File(file)); + try { + BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); + String jsonText = readAll(rd); + JSONObject json = new JSONObject(jsonText); + jsonText=null; + return json; + } finally { + is.close(); + } + } + + public static JSONObject readJsonFromUrl(String url, String file, boolean writeToFile) throws IOException, JSONException { + try { + InputStream is = new URL(url).openStream(); + BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); + String jsonText = readAll(rd); + if (writeToFile) { + writetoFile(new String[]{jsonText},file); + } + JSONObject json = new JSONObject(jsonText); + is.close(); + return json; + } catch (IOException e) { + return new JSONObject("{}"); + } + } + + public static JSONArray readJsonArrayFromUrl(String url, String file, boolean writeToFile) throws IOException, JSONException { + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + int responseCode = con.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode); + if (responseCode == HttpURLConnection.HTTP_OK) { // success + BufferedReader in = new BufferedReader(new InputStreamReader( + con.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + + // print result + System.out.println(response); + + return new JSONArray(response.toString()); + } else { + System.out.println("GET request not worked"); + return new JSONArray("[]"); + } + } + + public static void logToFile(String message, String filename) { + logToFile(message,filename,false); + } + + + public static void logToFile(String message, String filename, boolean outputToChatLog) { + File file = new File(filename); + try { + + if (!file.exists()) { + file.createNewFile(); + } + OutputStream out = new FileOutputStream(file,true); + Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8); + + PrintWriter pw = new PrintWriter(writer); + //pw.print('\uFEFF'); + pw.println(message); + pw.flush(); + pw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void writetoFile(String[] data, String filename) { + writetoFile(data,filename,true); + } + + public static void writetoFile(String[] data, String filename, boolean append) { + File file = new File(filename); + try { + + if (!file.exists()) { + file.createNewFile(); + } + + OutputStream out = new FileOutputStream(file,append); + Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8); + PrintWriter pw = new PrintWriter(writer); + //pw.print('\uFEFF'); + for (String s : data) { + pw.println(s); + } + pw.flush(); + pw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void copyFile(File source, File dest) throws IOException { + FileChannel sourceChannel = null; + FileChannel destChannel = null; + try { + sourceChannel = new FileInputStream(source).getChannel(); + destChannel = new FileOutputStream(dest).getChannel(); + destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); + }finally{ + sourceChannel.close(); + destChannel.close(); + } + } + + public static void copyFileDir(File sourcedir, File destdir) throws IOException { + FileChannel sourceChannel = null; + FileChannel destChannel = null; + destdir.mkdirs(); + try { + if (sourcedir.exists()) { + for (String name : sourcedir.list()) { + File f = new File(sourcedir,name); + sourceChannel = new FileInputStream(f).getChannel(); + destChannel = new FileOutputStream(new File(destdir,name)).getChannel(); + destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); + sourceChannel.close(); + destChannel.close(); + } + } + } + finally{ + + } + } + + public static void deleteFile(File filename) { + File file = filename; + if (file.exists()) { + //System.out.println("Trying to delete "+file); + if (file.isDirectory()) { + for (String name : file.list()) { + File f = new File(file,name); + deleteFile(f); + } + } + file.delete(); + //System.out.println(file+" deleted"); + } + } + + public static void deleteFile(String filename) { + File file = new File(filename); + deleteFile(file); + } + + + public static void downloadFileFromUrl(String url, String file) throws IOException, JSONException { + File filer = new File(file); + filer.createNewFile(); + + URL website = new URL(url); + HttpURLConnection connection = (HttpURLConnection) website.openConnection(); + /*for (String s : connection.getHeaderFields().keySet()) { + System.out.println(s+": "+connection.getHeaderFields().get(s)); + }*/ + connection.setRequestMethod("GET"); + //connection.setRequestProperty("Content-Type", "application/json"); + try { + ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream()); + FileOutputStream fos = new FileOutputStream(file); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + } catch (ConnectException e) { + System.out.println("Failed to connect, moving on..."); + } + } +} diff --git a/DivaBotGuardian/src/sig/utils/GithubUtils.java b/DivaBotGuardian/src/sig/utils/GithubUtils.java new file mode 100644 index 0000000..7cd1579 --- /dev/null +++ b/DivaBotGuardian/src/sig/utils/GithubUtils.java @@ -0,0 +1,35 @@ +package sig.utils; + +import java.io.IOException; +import java.util.Arrays; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class GithubUtils { + public static int getSizeOfFileFromLatestGithubCommit(String filename) { + try { + JSONObject data = FileUtils.readJsonFromUrl("https://api.github.com/repos/sigonasr2/sigIRCv2"); + String url = data.getString("commits_url").replace("{/sha}", ""); + JSONArray data_array = FileUtils.readJsonArrayFromUrl(url); + JSONObject dat = data_array.getJSONObject(0); + JSONObject datapoint1 = dat.getJSONObject("commit"); + datapoint1 = datapoint1.getJSONObject("tree"); + url = datapoint1.getString("url"); + data = FileUtils.readJsonFromUrl(url); + data_array = data.getJSONArray("tree"); + for (int i=0;i=0) { + String piece1 = sourcestring.substring(0,pos); + String piece2 = sourcestring.substring(pos+findstring.length(),sourcestring.length()); + //basemsg = basemsg.replaceFirst(e.getEmoteName(),e.getSpaceFiller()); + sourcestring = piece1+replacestring+piece2; + } + return sourcestring; + } + + public static boolean isAlphanumeric(String str) { + return str.matches("^[a-zA-Z0-9!\\-.?'\":,\\+ ]+$"); + } + + public static boolean isNumeric(String str) + { + if (str.length()>0) { + return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. + } else { + return false; + } + } + + public static boolean isInteger(String s, int radix) { + if(s.isEmpty()) return false; + for(int i = 0; i < s.length(); i++) { + if(i == 0 && s.charAt(i) == '-') { + if(s.length() == 1) return false; + else continue; + } + if(Character.digit(s.charAt(i),radix) < 0) return false; + } + return true; + } + + public static String convertSecondsToTimeFormat(int seconds) { + StringBuilder sb = new StringBuilder(); + int sec = seconds%60; + int min = (seconds/60)%60; + int hrs = (seconds/3600)%24; + if (hrs>0) { + if (hrs>=10) { + sb.append(hrs); + } else { + sb.append(0); + sb.append(hrs); + } + sb.append(":"); + } + if (min>=10) { + sb.append(min); + } else { + sb.append(0); + sb.append(min); + } + sb.append(":"); + if (sec>=10) { + sb.append(sec); + } else { + sb.append(0); + sb.append(sec); + } + return sb.toString(); + } + + public static String getActualChannelName() { + return sigIRC.channel.replaceFirst("#", ""); + } + + /** + * Converts a three CSV value to RGB value. + */ + public static Color convertStringToColor(String col) { + String[] split = col.split(","); + return new Color(Integer.parseInt(split[0]),Integer.parseInt(split[1]),Integer.parseInt(split[2])); + } + + public static List WrapText(String msg, Font font, double width) { + List displayMessage = new ArrayList(); + String rawmessage = msg; + int textWidth = (int)TextUtils.calculateStringBoundsFont(rawmessage, font).getWidth(); + int maxWidth = (int)width; + do { + rawmessage = BreakTextAtNextSection(rawmessage+" ",font,displayMessage,maxWidth); + textWidth = (int)TextUtils.calculateStringBoundsFont(rawmessage, font).getWidth(); + } while (textWidth>maxWidth); + if (rawmessage.length()>0) { + displayMessage.add(rawmessage); + } + return displayMessage; + //System.out.println(displayMessage+": "+messageDisplaySize); + } + + private static String BreakTextAtNextSection(String msg, Font font, List list, int maxWidth) { + int marker = 1; + int textWidth = (int)TextUtils.calculateStringBoundsFont(msg.substring(0, marker), font).getWidth(); + while (textWidth0) { + string.append(days); + } + if (hours>0) { + string.append(((string.length()>0)?":":"")+(hours%24)); + } + if (minutes>0) { + string.append(((string.length()>0)?":":"")+df.format((minutes%60))); + } + if (seconds>0) { + string.append(((string.length()>0)?":":"")+df.format((seconds%60))); + } + return string.toString(); + } +} diff --git a/DivaBotGuardian/src/sig/utils/WebUtils.java b/DivaBotGuardian/src/sig/utils/WebUtils.java new file mode 100644 index 0000000..3d6695f --- /dev/null +++ b/DivaBotGuardian/src/sig/utils/WebUtils.java @@ -0,0 +1,69 @@ +package sig.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.ContentBody; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.CoreProtocolPNames; +import org.apache.http.util.EntityUtils; + +public class WebUtils { + public static void POSTimage(String url,File file,Map params) { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost uploadFile = new HttpPost(url); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + for (String s : params.keySet()) { + builder.addTextBody(s, params.get(s), ContentType.TEXT_PLAIN); + } + try { + // This attaches the file to the POST: + builder.addBinaryBody( + "file", + new FileInputStream(file), + ContentType.APPLICATION_OCTET_STREAM, + file.getName() + ); + + HttpEntity multipart = builder.build(); + uploadFile.setEntity(multipart); + CloseableHttpResponse response; + response = httpClient.execute(uploadFile); + HttpEntity responseEntity = response.getEntity(); + String result = ""; + if (responseEntity != null) { + try (InputStream instream = responseEntity.getContent()) { + Scanner s = new Scanner(instream).useDelimiter("\\A"); + result = s.hasNext() ? s.next() : ""; + System.out.println(result); + instream.close(); + } catch (UnsupportedOperationException | IOException e) { + e.printStackTrace(); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } +}