Moved to Maven

This commit is contained in:
JKetelaar
2015-09-13 22:51:13 +02:00
parent a3bf8d0d0d
commit 52836a3e9a
303 changed files with 56775 additions and 35 deletions
@@ -0,0 +1,52 @@
package org.parabot.environment;
import org.parabot.core.Core;
import org.parabot.core.desc.ServerDescription;
import org.parabot.core.lib.Library;
import org.parabot.core.lib.javafx.JavaFX;
import org.parabot.core.lib.naga.Naga;
import org.parabot.core.parsers.servers.ServerParser;
import org.parabot.core.ui.components.VerboseLoader;
import org.parabot.environment.api.utils.WebUtil;
import java.util.LinkedList;
/**
*
* Initiliazes the bot environment
*
* @author Everel
*
*/
public class Environment {
/**
* Loads a new environment
*
* @param desc
*/
public static void load(final ServerDescription desc) {
LinkedList<Library> libs = new LinkedList<>();
libs.add(new JavaFX());
libs.add(new Naga());
for(Library lib : libs) {
if(!lib.hasJar()) {
Core.verbose("Downloading " + lib.getLibraryName() + "...");
VerboseLoader.setState("Downloading " + lib.getLibraryName() + "...");
WebUtil.downloadFile(lib.getDownloadLink(), lib.getJarFile(), VerboseLoader.get());
Core.verbose("Downloaded " + lib.getLibraryName() + ".");
}
Core.verbose("Initializing " + lib.getLibraryName());
lib.init();
}
Core.verbose("Loading server: " + desc.toString());
ServerParser.SERVER_CACHE.get(desc).run();
}
}
@@ -0,0 +1,25 @@
package org.parabot.environment;
/**
*
* This class is used for detecting the user's operating system
*
* @author Everel
*
*/
public enum OperatingSystem {
WINDOWS, LINUX, MAC, OTHER;
public static final OperatingSystem getOS() {
String str = System.getProperty("os.name").toLowerCase();
if (str.indexOf("win") > -1)
return OperatingSystem.WINDOWS;
if (str.indexOf("mac") > -1)
return OperatingSystem.MAC;
if (str.indexOf("nix") > -1 || str.indexOf("nux") > -1)
return OperatingSystem.LINUX;
return OperatingSystem.OTHER;
}
}
@@ -0,0 +1,17 @@
package org.parabot.environment.api.interfaces;
import java.awt.Graphics;
/**
*
* @author Everel
*
*/
public interface Paintable {
/**
* @param g
*/
public void paint(Graphics g);
}
@@ -0,0 +1,68 @@
package org.parabot.environment.api.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author JKetelaar
*/
public class FileUtil {
public static String getChecksum(File file){
if (file.isFile()) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
byte[] dataBytes = new byte[1024];
int nread;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
byte[] mdbytes = md.digest();
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
}
return null;
}
public static byte[] getChecksumBytes(File file) {
if (file.isFile()) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
byte[] dataBytes = new byte[1024];
int nread;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
return md.digest();
}
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
}
return null;
}
}
@@ -0,0 +1,17 @@
package org.parabot.environment.api.utils;
/**
* A simple class to filter things out of an collection
*
* @author Everel
*
* @param <F>
*/
public interface Filter<F> {
/**
* Determines if this object should be accepted
* @param f
* @return <b>true</b> to include this object, otherwise <b>false</b> to exclude.
*/
public boolean accept(F f);
}
@@ -0,0 +1,46 @@
package org.parabot.environment.api.utils;
import java.math.BigInteger;
/**
*
* Helper class for calculating setters for clients that uses multipliers
*
* @author Everel
*
*/
public class Multipliers {
/**
*
* @param multiplier
* the multiplier
* @param set
* the value you want to set
* @return the correct setter value
*/
public static int getIntSetter(int multiplier, int set) {
int bits = 32;
BigInteger quotient = new BigInteger(Integer.toString(multiplier));
BigInteger shift = BigInteger.ONE.shiftLeft(bits);
int value = quotient.modInverse(shift).intValue();
return value * set;
}
/**
*
* @param multiplier
* the multiplier
* @param set
* the value you want to set
* @return the correct setter value
*/
public static long getLongSetter(long multiplier, long set) {
int bits = 64;
BigInteger quotient = new BigInteger(Long.toString(multiplier));
BigInteger shift = BigInteger.ONE.shiftLeft(bits);
long value = quotient.modInverse(shift).longValue();
return value * set;
}
}
@@ -0,0 +1,132 @@
package org.parabot.environment.api.utils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.parabot.core.forum.AccountManager;
import org.parabot.core.forum.AccountManagerAccess;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Properties;
/**
* @author JKetelaar
*/
public class PBPreferences {
private static AccountManager manager;
private Properties properties;
private int scriptID;
public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
@Override
public final void setManager(AccountManager manager) {
PBPreferences.manager = manager;
}
};
public PBPreferences(int scriptID) {
this.scriptID = scriptID;
this.updateSettings();
}
private void updateSettings() {
properties = new Properties();
try {
JSONObject result = (JSONObject) WebUtil.getJsonParser().parse(
WebUtil.getContents("http://bdn.parabot.org/api/v2/user/preferences/" + scriptID,
"apikey=" + manager.getAccount().getApi())
);
JSONArray resultArray;
if ((resultArray = ((JSONArray) result.get("result"))) != null) {
for(Object rObject : resultArray) {
JSONObject resultObject = (JSONObject) rObject;
for (Object map : resultObject.entrySet()) {
Map.Entry<?, ?> pairs = (Map.Entry<?, ?>) map;
properties.put(pairs.getKey(), pairs.getValue());
}
}
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
/**
* Change a setting
* @param key
* @param value
*/
public void adjustSettings(Object key, Object value) {
this.addSetting(key, value);
}
/**
* Get a setting value
* @param key
* @return
*/
public Object getSetting(Object key){
return this.properties.get(key);
}
/**
* Get a setting value as string
* @param key
* @return
*/
public String getSetting(String key){
return this.properties.getProperty(key);
}
/**
* Remove a setting
* @param key
*/
public void removeSetting(Object key){
try {
JSONObject result = (JSONObject) WebUtil.getJsonParser().parse(
WebUtil.getContents("http://bdn.parabot.org/api/v2/user/preferences/set/",
"apikey=" + manager.getAccount().getApi() +
"&key=" + URLEncoder.encode(String.valueOf(key), "UTF-8") +
"&script=" + String.valueOf(scriptID)
)
);
if ((boolean)result.get("result")){
this.properties.remove(key);
}
} catch (ParseException | MalformedURLException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Add a setting
* @param key
* @param value
*/
public void addSetting(Object key, Object value){
try {
JSONObject result = (JSONObject) WebUtil.getJsonParser().parse(
WebUtil.getContents("http://bdn.parabot.org/api/v2/user/preferences/set/",
"apikey=" + manager.getAccount().getApi() +
"&key=" + URLEncoder.encode(String.valueOf(key), "UTF-8") +
"&value=" + URLEncoder.encode(String.valueOf(value), "UTF-8") +
"&script=" + String.valueOf(scriptID)
)
);
if ((boolean)result.get("result")){
this.properties.put(key, value);
}
} catch (ParseException | MalformedURLException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,28 @@
package org.parabot.environment.api.utils;
/**
*
* A random class is used for generating random numbers
*
* @author Everel
*
*/
public class Random {
private final static java.util.Random RANDOM = new java.util.Random();
/**
* Randomizes a number between minimum and maximum
*
* @param min
* @param max
* @return randomized number
*/
public static int between(final int min, final int max) {
try {
return min + (max == min ? 0 : RANDOM.nextInt(max - min));
} catch (Exception e) {
return min + (max - min);
}
}
}
@@ -0,0 +1,30 @@
package org.parabot.environment.api.utils;
/**
*
* @author mkyong
*
*/
public class StringUtils {
public static String convertHexToString(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for (int i = 0; i < hex.length() - 1; i += 2) {
// grab the hex in pairs
String output = hex.substring(i, (i + 2));
// convert hex to decimal
int decimal = Integer.parseInt(output, 16);
// convert the decimal to character
sb.append((char) decimal);
temp.append(decimal);
}
return sb.toString();
}
}
@@ -0,0 +1,68 @@
package org.parabot.environment.api.utils;
import org.parabot.environment.scripts.framework.SleepCondition;
/**
*
* Holds various Time utilities
*
* @author Everel
*
*/
public final class Time {
/**
* Sleeps for a given amount of time
* @param ms
*/
public static void sleep(final int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
*
* @param minumum
* @param maximum
*/
public static void sleep(final int minumum, final int maximum) {
try {
Thread.sleep(Random.between(minumum, maximum));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Sleeps until the SleepCondition is valid.
*
* @param conn
* the condition.
* @param timeout
* the time in miliseconds before it stops sleeping.
* @return whether it ran successfully without timing out.
*/
public static boolean sleep(SleepCondition conn, int timeout) {
long start = System.currentTimeMillis();
while (!conn.isValid()) {
if (start + timeout < System.currentTimeMillis()) {
return false;
}
Time.sleep(50);
}
return true;
}
/**
* Gets current time in milliseconds
* @return time in ms
*/
public static long get() {
return System.currentTimeMillis();
}
}
@@ -0,0 +1,120 @@
package org.parabot.environment.api.utils;
/**
*
* A simple timer class
*
* @author Everel, Parameter
*
*/
public class Timer {
private long start;
private long end;
/**
* Timer Constructor
*
* @param start
*/
public Timer(long end) {
start = System.currentTimeMillis();
this.end = System.currentTimeMillis() + end;
}
/**
* Timer Constructor
*/
public Timer() {
this(0);
}
/**
* Determines the remaining time left.
*
* @return the remaining time.
*/
public long getRemaining() {
return end - System.currentTimeMillis();
}
/**
* Determines if the end time has been reached, does not mean it stopped
* running.
*/
public boolean isFinished() {
return System.currentTimeMillis() > end;
}
/**
* Stops and resets the timer
*/
public void restart() {
stop();
reset();
}
/**
* Resets the timer if stopped
*/
public void reset() {
if (start == 0) {
start = System.currentTimeMillis();
}
}
/**
* Resets the timer
*/
public void stop() {
end = (end - start) + System.currentTimeMillis();
start = 0;
}
/**
* Determines if timer is running
*
* @return <b>true</b> if timer is running
*/
public boolean isRunning() {
return start != 0;
}
/**
* Gets the run time in long millis.
*
* @return the elapsed time.
*/
public long getElapsedTime() {
return System.currentTimeMillis() - start;
}
/**
* Calculates hourly gains based on given variable
*
* @param gained
* variable
* @return hourly gains
*/
public int getPerHour(final int gained) {
return (int) ((gained) * 3600000D / (System.currentTimeMillis() - start));
}
/**
* Generates string based on HH:MM:SS
*
* @return String
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
long elapsed = getElapsedTime();
int second = (int) (elapsed / 1000 % 60);
int minute = (int) (elapsed / 60000 % 60);
int hour = (int) (elapsed / 3600000 % 60);
b.append(hour < 10 ? "0" : "").append(hour).append(":");
b.append(minute < 10 ? "0" : "").append(minute).append(":");
b.append(second < 10 ? "0" : "").append(second);
return new String(b);
}
}
@@ -0,0 +1,311 @@
package org.parabot.environment.api.utils;
import org.json.simple.parser.JSONParser;
import org.parabot.core.io.ProgressListener;
import org.parabot.core.io.SizeInputStream;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
*
* A WebUtil class fetches data from an URL
*
* @author Everel
*
*/
public class WebUtil {
private static JSONParser jsonParser;
private static String agent = "Mozilla/5.0 (Wind0ws NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
/**
* Agent to set at a URL connection
*
* @param userAgent
*/
public static void setUserAgent(final String userAgent) {
agent = userAgent;
}
/**
* Gets useragent
*
* @return useragent
*/
public static String getUserAgent() {
return agent;
}
/**
* Fetches content of a page
*
* @param location
* @return contents of page
* @throws MalformedURLException
*/
public static String getContents(final String location)
throws MalformedURLException {
return getContents(new URL(location));
}
public static String getContents(final String location, String parameters) throws MalformedURLException {
return getContents(new URL(location), parameters);
}
/**
* Get contents from URL
*
* @param url
* @return page contents
*/
public static String getContents(final URL url) {
return getContents(getConnection(url));
}
public static String getContents(final URL url, final String parameters) {
return getContents(getConnection(url), parameters);
}
/**
* Gets contents from URLConnection
*
* @param urlConnection
* @return page contents
*/
public static String getContents(URLConnection urlConnection) {
try {
final BufferedReader in = getReader(urlConnection);
final StringBuilder builder = new StringBuilder();
String line;
if (in != null) {
while ((line = in.readLine()) != null) {
builder.append(line);
}
in.close();
}
return builder.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
public static String getContents(URLConnection urlConnection, String parameters) {
try {
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(parameters);
wr.flush();
wr.close();
final BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
final StringBuilder builder = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Gets buffered reader from string url
*
* @param url
* @return bufferedreader
*/
public static BufferedReader getReader(final String url) {
try {
return getReader(new URL(url));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
/**
* Gets BufferedReader from URL
*
* @param url
* @return BufferedReader from URL
*/
public static BufferedReader getReader(final URL url) {
return getReader(getConnection(url));
}
public static BufferedReader getReader(final URLConnection urlConnection) {
try {
return new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Gets inputstream from url
*
* @param url
* @return inputstream from url
*/
public static InputStream getInputStream(final URL url) {
final URLConnection con = getConnection(url);
try {
return con.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Opens a connection
*
* @param url
* @return URLConnection to URL
*/
public static URLConnection getConnection(final URL url) {
try {
final URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", agent);
return con;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
public static BufferedReader getReader(final URL url, String username, String password) {
try {
String data = URLEncoder.encode("username", "UTF-8") + "=" + username;
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + password;
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
return new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
public static URLConnection getConnection(final URL url, String username, String password) {
try {
String data = URLEncoder.encode("username", "UTF-8") + "=" + username;
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + password;
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
return connection;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Downloads a file on the internet
* @param url
* @param destination
* @param listener
*/
public static void downloadFile(final URL url, final File destination,
final ProgressListener listener) {
try {
final URLConnection connection = getConnection(url);
int size = connection.getContentLength();
SizeInputStream sizeInputStream = new SizeInputStream(
connection.getInputStream(), size, listener);
BufferedInputStream in = new BufferedInputStream(sizeInputStream);
FileOutputStream fileOut = new FileOutputStream(destination);
try {
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fileOut.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fileOut != null)
fileOut.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* Downloads a file on the internet
* @param url
* @param destination
* @param listener
*/
public static void downloadFile(final URL url, final File destination,
final ProgressListener listener, String username, String password) {
try {
final URLConnection connection = getConnection(url, username, password);
int size = connection.getContentLength();
SizeInputStream sizeInputStream = new SizeInputStream(
connection.getInputStream(), size, listener);
BufferedInputStream in = new BufferedInputStream(sizeInputStream);
FileOutputStream fileOut = new FileOutputStream(destination);
try {
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fileOut.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fileOut != null)
fileOut.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* Converts file format to url format
* @param file
* @return url to file
*/
public static URL toURL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
public static JSONParser getJsonParser() {
if (jsonParser == null){
jsonParser = new JSONParser();
}
return jsonParser;
}
}
@@ -0,0 +1,225 @@
package org.parabot.environment.input;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Random;
import org.parabot.core.Context;
/**
*
* Virtual keyboard, dispatches key events to a component.
*
* @author Everel, Matt, Dane
*
*/
public class Keyboard implements KeyListener {
private static HashMap<Character, Character> specialChars;
private Component component;
private long pressTime;
public Keyboard(Component component) {
this.component = component;
}
public static Keyboard getInstance() {
return Context.getInstance().getKeyboard();
}
static {
char[] spChars = { '~', '!', '@', '#', '%', '^', '&', '*', '(', ')',
'_', '+', '{', '}', ':', '<', '>', '?', '"', '|' };
char[] replace = { '`', '1', '2', '3', '5', '6', '7', '8', '9', '0',
'-', '=', '[', ']', ';', ',', '.', '/', '\'', '\\' };
specialChars = new HashMap<Character, Character>(spChars.length);
for (int x = 0; x < spChars.length; ++x)
specialChars.put(spChars[x], replace[x]);
}
private static long getRandom() {
Random rand = new Random();
return rand.nextInt(100) + 40;
}
public void sendKeys(String s) {
pressTime = System.currentTimeMillis();
for (char c : s.toCharArray())
for (KeyEvent ke : createKeyClick(component, c)) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendKeyEvent(ke);
}
clickKey(10);
}
public void clickKey(char c) {
pressTime = System.currentTimeMillis();
for (KeyEvent ke : createKeyClick(component, c))
sendKeyEvent(ke);
}
public void clickKey(int keyCode) {
pressTime = System.currentTimeMillis();
for (KeyEvent ke : createKeyClick(component, keyCode))
sendKeyEvent(ke);
}
public void pressKey(int keyCode) {
pressTime = System.currentTimeMillis();
KeyEvent ke = createKeyPress(component, keyCode);
sendKeyEvent(ke);
}
public void releaseKey(int keyCode) {
pressTime = System.currentTimeMillis();
KeyEvent ke = createKeyRelease(component, keyCode);
sendKeyEvent(ke);
}
private KeyEvent[] createKeyClick(Component target, char c) {
pressTime += 2 * getRandom();
Character newChar = specialChars.get(c);
int keyCode = Character.toUpperCase((newChar == null) ? c : newChar);
if (Character.isLowerCase(c)
|| (!Character.isLetter(c) && (newChar == null))) {
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, 0, keyCode, c);
KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
pressTime, 0, 0, c);
pressTime += getRandom();
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime, 0, keyCode, c);
return new KeyEvent[] { pressed, typed, released };
} else {
KeyEvent shiftDown = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, KeyEvent.SHIFT_MASK, KeyEvent.VK_SHIFT,
KeyEvent.CHAR_UNDEFINED);
pressTime += getRandom();
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
pressTime, KeyEvent.SHIFT_MASK, 0, c);
pressTime += getRandom();
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
pressTime += getRandom();
KeyEvent shiftUp = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime, 0, KeyEvent.VK_SHIFT, KeyEvent.CHAR_UNDEFINED);
return new KeyEvent[] { shiftDown, pressed, typed, released,
shiftUp };
}
}
private KeyEvent[] createKeyClick(Component target, int keyCode) {
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_SHIFT:
modifier = KeyEvent.SHIFT_MASK;
break;
case KeyEvent.VK_ALT:
modifier = KeyEvent.ALT_MASK;
break;
case KeyEvent.VK_CONTROL:
modifier = KeyEvent.CTRL_MASK;
break;
}
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
return new KeyEvent[] { pressed, released };
}
private KeyEvent createKeyPress(Component target, int keyCode) {
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_SHIFT:
modifier = KeyEvent.SHIFT_MASK;
break;
case KeyEvent.VK_ALT:
modifier = KeyEvent.ALT_MASK;
break;
case KeyEvent.VK_CONTROL:
modifier = KeyEvent.CTRL_MASK;
break;
}
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
return pressed;
}
private KeyEvent createKeyRelease(Component target, int keyCode) {
@SuppressWarnings("unused")
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_SHIFT:
modifier = KeyEvent.SHIFT_MASK;
break;
case KeyEvent.VK_ALT:
modifier = KeyEvent.ALT_MASK;
break;
case KeyEvent.VK_CONTROL:
modifier = KeyEvent.CTRL_MASK;
break;
}
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
return released;
}
public void sendKeyEvent(KeyEvent e) {
for (KeyListener kl : component.getKeyListeners()) {
if(kl instanceof Keyboard) {
continue;
}
if (!e.isConsumed()) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
kl.keyPressed(e);
break;
case KeyEvent.KEY_RELEASED:
kl.keyReleased(e);
break;
case KeyEvent.KEY_TYPED:
kl.keyTyped(e);
break;
}
}
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
@@ -0,0 +1,163 @@
package org.parabot.environment.input;
import org.parabot.core.Context;
import org.parabot.environment.api.utils.Time;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
/**
*
* A virtual mouse, dispatches mouse events to a component
*
* @author Everel
*
*/
public class Mouse implements MouseListener, MouseMotionListener {
private Component component;
private int x;
private int y;
public Mouse(Component component) {
this.component = component;
}
public static Mouse getInstance() {
return Context.getInstance().getMouse();
}
/**
* Moves the mouse to the given point and clicks
* @param x
* @param y
* @param left
*/
public void click(final int x, final int y, final boolean left) {
moveMouse(x, y);
Time.sleep(50, 200);
pressMouse(x, y, left);
Time.sleep(10, 100);
releaseMouse(x, y, left);
Time.sleep(10, 100);
clickMouse(x, y, left);
}
public void pressMouse(int x, int y, boolean left) {
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, x,
y, 1, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
for(MouseListener l : component.getMouseListeners()) {
if(!(l instanceof Mouse)) {
l.mousePressed(me);
}
}
}
public void click(final Point p, final boolean left) {
click(p.x, p.y, left);
}
public void click(final Point p) {
click(p.x, p.y, true);
}
public void clickMouse(int x, int y, boolean left) {
try {
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, x,
y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
for(MouseListener l : component.getMouseListeners()) {
if(!(l instanceof Mouse)) {
l.mouseClicked(me);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void releaseMouse(int x, int y, boolean left) {
try {
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_RELEASED, System.currentTimeMillis(), 0, x,
y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
for(MouseListener l : component.getMouseListeners()) {
if(!(l instanceof Mouse)) {
l.mouseReleased(me);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Moves the mouse cursor to the given location
* @param x
* @param y
*/
public void moveMouse(int x, int y) {
try {
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), 0, x,
y, 0, false);
for(MouseMotionListener l : component.getMouseMotionListeners()) {
if(!(l instanceof Mouse)) {
l.mouseMoved(me);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Mouse cursor current location
* @return point
*/
public Point getPoint() {
return new Point(x, y);
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
@@ -0,0 +1,58 @@
package org.parabot.environment.scripts;
import org.parabot.core.ui.images.Images;
import java.awt.image.BufferedImage;
import java.util.HashMap;
/**
*
* Holds script categories
*
* @author Dane, Paradox
*
*/
public enum Category
{
AGILITY, COMBAT, COOKING, CRAFTING, CONSTRUCTION, DUNGEONEERING, FARMING, FIREMAKING, FISHING, FLETCHING, HERBLORE, HUNTER, MAGIC, MINIGAMES, MINING, OTHER, PRAYER, RUNECRAFTING, SLAYER, SMITHING, THIEVING, UTILITY, WOODCUTTING;
/**
* Gets image belonging to this category
* @return icon
*/
public BufferedImage getIcon() {
return Category.getIcon(this.name().toLowerCase());
}
/**
* Gets category icon image from filename
* @param s Name of the image - used for the hashmap index
* @return icon
*/
public static BufferedImage getIcon(String s) {
if (images.get(s) == null) {
images.put(s, Images.getResource("/org/parabot/core/ui/images/category/" + s + ".png"));
}
return images.get(s);
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(name().charAt(0));
b.append(name().toLowerCase().substring(1));
return new String(b);
}
/**
* Cache
*/
private static HashMap<String, BufferedImage> images = new HashMap<>();
static {
images.put("script", Images.getResource("/org/parabot/core/ui/images/category/script.png"));
}
}
@@ -0,0 +1,67 @@
package org.parabot.environment.scripts;
import java.util.Collection;
import org.parabot.environment.scripts.framework.AbstractFramework;
import org.parabot.environment.scripts.framework.LoopTask;
import org.parabot.environment.scripts.framework.Strategy;
/**
*
* Holds various script frameworks
*
* @author Everel
*
*/
public class Frameworks {
public static Looper getLooper(LoopTask loopTask) {
return new Looper(loopTask);
}
public static StrategyWorker getStrategyWorker(Collection<Strategy> strategies) {
return new StrategyWorker(strategies);
}
}
class Looper extends AbstractFramework {
private LoopTask loopTask = null;
public Looper(LoopTask loopTask) {
this.loopTask = loopTask;
}
@Override
public boolean execute() {
int sleepTime = loopTask.loop();
if(sleepTime < 0) {
return false;
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
class StrategyWorker extends AbstractFramework {
private Collection<Strategy> strategies;
public StrategyWorker(Collection<Strategy> strategies) {
this.strategies = strategies;
}
@Override
public boolean execute() {
for(Strategy s : strategies) {
if(s.activate()) {
s.execute();
return true;
}
}
return true;
}
}
@@ -0,0 +1,184 @@
package org.parabot.environment.scripts;
import org.parabot.core.Context;
import org.parabot.core.Core;
import org.parabot.core.ui.BotUI;
import org.parabot.core.ui.Logger;
import org.parabot.environment.api.utils.PBPreferences;
import org.parabot.environment.api.utils.Time;
import org.parabot.environment.scripts.framework.*;
import org.parabot.environment.scripts.framework.Frameworks;
import org.parabot.environment.scripts.randoms.Random;
import java.util.Collection;
/**
*
* Script template, scripts are 'add-ons' which executes various tasks in-game
*
* @author Everel
*
*/
public class Script implements Runnable {
public static final int TYPE_STRATEGY = 0;
public static final int TYPE_LOOP = 1;
public static final int TYPE_OTHER = 2;
public static final int STATE_RUNNING = 0;
public static final int STATE_PAUSE = 1;
public static final int STATE_STOPPED = 2;
private Collection<Strategy> strategies;
private PBPreferences preferences;
private AbstractFramework frameWork;
private int state;
private int frameWorkType;
private int scriptID;
public boolean onExecute() {
return true;
}
public void onFinish() {
}
public final void provide(final Collection<Strategy> strategies) {
this.strategies = strategies;
}
public final int getFrameWorkType() {
return frameWorkType;
}
public final void setFrameWork(int frameWorkType) {
if(frameWorkType < 0 || frameWorkType > 2) {
throw new RuntimeException("Invalid framework type");
}
this.frameWorkType = frameWorkType;
}
public final void setAbstractFrameWork(AbstractFramework f) {
this.frameWork = f;
}
public final void addRandom(Random random) {
Context.getInstance().getRandomHandler().addRandom(random);
}
@Override
public final void run() {
Context context = Context.getInstance();
Core.verbose("Initializing script...");
context.getServerProvider().initScript(this);
Core.verbose("Done.");
if(!onExecute()) {
Core.verbose("Script#onExecute returned false, unloading and stopping script...");
context.getServerProvider().unloadScript(this);
this.state = STATE_STOPPED;
Core.verbose("Done.");
return;
}
Core.verbose("Detecting script framework...");
context.setRunningScript(this);
BotUI.getInstance().toggleRun();
if(this instanceof LoopTask) {
Core.verbose("Script framework detected: LoopTask");
frameWorkType = TYPE_LOOP;
frameWork = Frameworks.getLooper((LoopTask) this);
} else if(strategies != null && !strategies.isEmpty()) {
Core.verbose("Script framework detected: Strategies");
frameWorkType = TYPE_STRATEGY;
frameWork = Frameworks.getStrategyWorker(strategies);
} else {
Core.verbose("Unknown script framework: Other");
frameWorkType = TYPE_OTHER;
}
Core.verbose("Running script...");
Logger.addMessage("Script started.");
try {
while(this.state != STATE_STOPPED) {
if(context.getRandomHandler().checkAndRun()) {
continue;
}
if(this.state == STATE_PAUSE) {
sleep(500);
continue;
}
if(!frameWork.execute()) {
break;
}
}
} catch (Throwable t) {
t.printStackTrace();
}
Core.verbose("Script stopped/finished, unloading and stopping...");
onFinish();
Logger.addMessage("Script stopped.");
context.getServerProvider().unloadScript(this);
this.state = STATE_STOPPED;
context.setRunningScript(null);
if (context.getUlirathaClient() != null) {
context.getUlirathaClient().disconnect();
context.setUlirathaClient(null);
}
BotUI.getInstance().toggleRun();
Core.verbose("Done.");
}
/**
* Sleeps until the SleepCondition is valid.
*
* <B>DEPRECATED!</b> use {@link Time#sleep(SleepCondition, int)}
*
* @param conn
* the condition.
* @param timeout
* the time in miliseconds before it stops sleeping.
* @return whether it ran successfully without timing out.
*/
@Deprecated
public final boolean sleep(SleepCondition conn, int timeout) {
return Time.sleep(conn, timeout);
}
/**
* Sets the script's state
* @param state
*/
public final void setState(final int state) {
if(state < 0 || state > 2) {
throw new IllegalArgumentException("Illegal state");
}
this.state = state;
}
/**
* Sleeps for an amount of milliseconds
* @param ms
*/
public final void sleep(int ms) {
Time.sleep(ms);
}
public int getState() {
return state;
}
public PBPreferences getPreferences(){
if (this.preferences == null){
this.preferences = new PBPreferences(scriptID);
}
return this.preferences;
}
public void setScriptID(int scriptID){
this.scriptID = scriptID;
}
}
@@ -0,0 +1,30 @@
package org.parabot.environment.scripts;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A script manifest, holds all script data
* @author Everel
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ScriptManifest {
String author();
String name();
Category category();
double version();
String description();
String[] servers();
boolean vip() default false;
boolean premium() default false;
}
@@ -0,0 +1,100 @@
package org.parabot.environment.scripts.executers;
import org.parabot.core.Configuration;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.forum.AccountManager;
import org.parabot.core.forum.AccountManagerAccess;
import org.parabot.core.ui.utils.UILog;
import org.parabot.environment.api.utils.WebUtil;
import org.parabot.environment.scripts.Script;
import org.parabot.environment.scripts.loader.JavaScriptLoader;
import org.parabot.environment.scripts.uliratha.UlirathaExecuter;
import javax.swing.*;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLConnection;
/**
*
* Loads a script from the BDN
*
* @author Everel
*
*/
public class BDNScriptsExecuter extends ScriptExecuter {
private static AccountManager manager;
public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
@Override
public final void setManager(AccountManager manager) {
BDNScriptsExecuter.manager = manager;
}
};
private int id = -1;
public BDNScriptsExecuter(final int id) {
this.id = id;
}
@Override
public void run(ThreadGroup tg) {
try {
final URLConnection urlConnection = WebUtil.getConnection(new URL(
Configuration.GET_SCRIPT + this.id), manager.getAccount().getURLUsername(), manager.getAccount().getURLPassword());
final String contentType = urlConnection.getHeaderField("Content-type");
switch (contentType) {
case "text/html":
// failed to fetch script
UILog.log("Error", "Failed to load BDN script, error: [Page returned: " + WebUtil.getContents(urlConnection) + "]", JOptionPane.ERROR_MESSAGE);
break;
case "application/jar":
//// JAR LOADING PART ////////
// succesfull request, jar returned
final ClassPath classPath = new ClassPath();
classPath.addJar(urlConnection);
final JavaScriptLoader loader = new JavaScriptLoader(classPath);
final String[] scriptClasses = loader.getScriptClassNames();
if (scriptClasses == null || scriptClasses.length == 0) {
UILog.log("Error", "Failed to load BDN script, error: [No script found in jar file.]", JOptionPane.ERROR_MESSAGE);
return;
} else if (scriptClasses.length > 1) {
UILog.log("Error", "Failed to load BDN script, error: [Multiple scripts found in jar file.]");
return;
}
final String className = scriptClasses[0];
try {
final Class<?> scriptClass = loader.loadClass(className);
final Constructor<?> con = scriptClass.getConstructor();
final Script script = (Script) con.newInstance();
script.setScriptID(this.id);
super.finalize(tg, script);
if (manager.getAccount().getApi() != null) {
new UlirathaExecuter(manager.getAccount().getApi()).start(this.id);
}
} catch (NoClassDefFoundError | ClassNotFoundException ignored) {
UILog.log("Error", "Failed to load BDN script, error: [This server provider does not support this script]", JOptionPane.ERROR_MESSAGE);
} catch (Throwable t) {
t.printStackTrace();
UILog.log("Error", "Failed to load BDN script, post the stacktrace/error on the parabot forums.", JOptionPane.ERROR_MESSAGE);
}
//// END JAR LOADING ////
break;
default:
UILog.log("Error", "Failed to load BDN script, error: [Unknown content type: " + contentType + "]", JOptionPane.ERROR_MESSAGE);
break;
}
} catch (Throwable t) {
t.printStackTrace();
UILog.log("Error", "Failed to load BDN script, post the stacktrace/error on the parabot forums.", JOptionPane.ERROR_MESSAGE);
}
}
}
@@ -0,0 +1,30 @@
package org.parabot.environment.scripts.executers;
import org.parabot.environment.scripts.Script;
import java.lang.reflect.Constructor;
/**
*
* Loads a locally stored script
*
* @author Everel
*
*/
public class LocalScriptExecuter extends ScriptExecuter {
private Constructor<?> scriptConstructor;
public LocalScriptExecuter(final Constructor<?> scriptConstructor) {
this.scriptConstructor = scriptConstructor;
}
@Override
public void run(ThreadGroup tg) {
try {
super.finalize(tg, (Script) scriptConstructor.newInstance(new Object[] { }));
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@@ -0,0 +1,27 @@
package org.parabot.environment.scripts.executers;
import org.parabot.environment.scripts.Script;
/**
*
* Executes a script
*
* @author Everel
*
*/
public abstract class ScriptExecuter {
public abstract void run(final ThreadGroup tg);
/**
* Start script.
* @param tg
* @param script
*/
public final void finalize(final ThreadGroup tg, final Script script) {
Thread thread = new Thread(tg, script);
thread.start();
}
}
@@ -0,0 +1,18 @@
package org.parabot.environment.scripts.framework;
/**
*
* Abstract framework for a script
*
* @author Everel
*
*/
public abstract class AbstractFramework {
/**
* Executes this frame
* @return <b>true</b> if it should keep executing this framework, otherwise <b>false</b>.
*/
public abstract boolean execute();
}
@@ -0,0 +1,63 @@
package org.parabot.environment.scripts.framework;
import java.util.Collection;
/**
*
* Holds various script frameworks
*
* @author Everel
*
*/
public class Frameworks {
public static Looper getLooper(LoopTask loopTask) {
return new Looper(loopTask);
}
public static StrategyWorker getStrategyWorker(Collection<Strategy> strategies) {
return new StrategyWorker(strategies);
}
}
class Looper extends AbstractFramework {
private LoopTask loopTask = null;
public Looper(LoopTask loopTask) {
this.loopTask = loopTask;
}
@Override
public boolean execute() {
int sleepTime = loopTask.loop();
if(sleepTime < 0) {
return false;
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
class StrategyWorker extends AbstractFramework {
private Collection<Strategy> strategies;
public StrategyWorker(Collection<Strategy> strategies) {
this.strategies = strategies;
}
@Override
public boolean execute() {
for(Strategy s : strategies) {
if(s.activate()) {
s.execute();
return true;
}
}
return true;
}
}
@@ -0,0 +1,18 @@
package org.parabot.environment.scripts.framework;
/**
*
* A LoopTask interface is used to keep calling the loop method which should return the sleep time
*
* @author Everel
*
*/
public interface LoopTask {
/**
*
* @return sleepTime in ms
*/
public int loop();
}
@@ -0,0 +1,18 @@
package org.parabot.environment.scripts.framework;
/**
* Keeps sleeping till a condition is valid
*
* @author Everel
*
*/
public interface SleepCondition {
/**
* Determine if condition is valid
* @return <b>true</b> if valid, otherwise <b>false</b>.
*/
public boolean isValid();
}
@@ -0,0 +1,22 @@
package org.parabot.environment.scripts.framework;
/**
* Strategy framework for scripts
*
* @author Everel
*
*/
public interface Strategy {
/**
* Whether to activate this strategy
* @return <b>true</b> if this strategy should be executed, otherwise <b>false</b>.
*/
public boolean activate();
/**
* Executes this strategy
*/
public void execute();
}
@@ -0,0 +1,43 @@
package org.parabot.environment.scripts.loader;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.tree.ClassNode;
import org.parabot.core.asm.ASMClassLoader;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.scripts.Script;
/**
*
* An environment to load a script
*
* @author Everel
*
*
*/
public class JavaScriptLoader extends ASMClassLoader {
private ClassPath classPath;
public JavaScriptLoader(ClassPath classPath) {
super(classPath);
this.classPath = classPath;
}
/**
* Gets all classes that extends ServerProvider
* @return string array of class names that extends ServerProvider
*/
public final String[] getScriptClassNames() {
final List<String> classNames = new ArrayList<String>();
for (ClassNode c : classPath.classes.values())
if (c.superName.replace('/', '.').equals(
Script.class.getName())) {
classNames.add(c.name.replace('/', '.'));
}
return classNames.toArray(new String[classNames.size()]);
}
}
@@ -0,0 +1,33 @@
package org.parabot.environment.scripts.randoms;
/**
*
* @author Everel
*
*/
public interface Random {
/**
* Determines whether this random should activate
* @return <b>true</b> if this random should activate
*/
public boolean activate();
/**
* Executes this random
*/
public void execute();
/**
* Returns the name of the random
* @return Name of the random
*/
public String getName();
/**
* Returns the name of the server which the random is made for
* @return Name of the server
*/
public String getServer();
}
@@ -0,0 +1,108 @@
package org.parabot.environment.scripts.randoms;
import org.parabot.core.Core;
import org.parabot.core.ui.Logger;
import java.util.ArrayList;
/**
*
* @author Everel
*
*/
public class RandomHandler {
private ArrayList<Random> randoms;
/**
* The randoms that will actually run
*/
private ArrayList<Random> activeRandoms;
public RandomHandler() {
this.randoms = new ArrayList<>();
this.activeRandoms = new ArrayList<>();
}
/**
* Adds a random to the random list
* @param random The random that will be added to the arraylist
*/
public void addRandom(Random random) {
if(random == null) {
throw new NullPointerException("Null random");
}
for(Random r : randoms) {
if(r.getClass() == random.getClass()) {
Core.verbose("Ignored added random, duplicate.");
return;
}
}
randoms.add(random);
setActive(random);
}
/**
* Adds a random to the active randoms
* @param random
*/
public void setActive(Random random){
this.activeRandoms.add(random);
}
/**
* Adds a random to the active randoms
* @param random
*/
public void setActive(String random){
for (Random r : this.randoms){
if (r.getName().equalsIgnoreCase(random.toLowerCase())){
this.activeRandoms.add(r);
}
}
}
/**
* Sets the whole random arraylist to the arraylist given as argument
* @param randoms The new random arraylist
*/
public void setRandoms(ArrayList<Random> randoms){
this.randoms = randoms;
}
/**
* Clears all added randoms
*/
public void clearRandoms() {
this.randoms.clear();
}
/**
* Clears all active randoms
*/
public void clearActiveRandoms(){
this.activeRandoms.clear();
}
/**
* Checks if random occurs and runs it
* @return returns <b>true</b> if a random has been executed, otherwise <b>false</b>
*/
public boolean checkAndRun() {
for(Random r : this.activeRandoms) {
if(r.activate()) {
Logger.addMessage("Running random '" + r.getName() + "'");
r.execute();
return true;
}
}
return false;
}
public ArrayList<Random> getRandoms(){
return this.randoms;
}
public ArrayList<Random> getActiveRandoms(){
return this.activeRandoms;
}
}
@@ -0,0 +1,158 @@
package org.parabot.environment.scripts.uliratha;
import naga.ExceptionObserver;
import naga.NIOService;
import naga.NIOSocket;
import naga.SocketObserver;
import naga.packetreader.RegularPacketReader;
import naga.packetwriter.RegularPacketWriter;
import org.parabot.core.ui.Logger;
import java.io.*;
/**
* @author JKetelaar
*/
public class UlirathaClient extends Thread {
private String host;
private int port;
private NIOSocket socket;
private boolean connected;
private int scriptID;
private String api;
private boolean valid;
public UlirathaClient(String host, int port, int scriptID, String api) {
this.host = host;
this.port = port;
this.scriptID = scriptID;
this.api = api;
}
@Override
public void run() {
connect();
}
private void connect() {
try {
NIOService service = new NIOService();
service.setExceptionObserver(new ExceptionObserver() {
@Override
public void notifyExceptionThrown(Throwable throwable) {
throwable.printStackTrace();
if (valid) {
reconnect();
connected = false;
}
}
});
socket = service.openSocket(host, port);
socket.setPacketReader(new RegularPacketReader(4, true));
socket.setPacketWriter(new RegularPacketWriter(4, true));
socket.listen(new SocketObserver() {
public void connectionOpened(NIOSocket nioSocket) {
try {
sendObjects(nioSocket, new Object[]{76, scriptID, api});
} catch (IOException e) {
e.printStackTrace();
}
}
public void packetReceived(NIOSocket socket, byte[] packet) {
try {
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(packet));
int packetID = stream.readInt();
switch (packetID){
case 75:
valid = stream.readBoolean();
if (valid) {
Logger.addMessage("We're connected with the Uliratha server!");
connected = true;
}else{
socket.close();
}
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void packetSent(NIOSocket nioSocket, Object o) {
}
public void connectionBroken(NIOSocket nioSocket, Exception exception) {
if (valid) {
Logger.addMessage("We lost connection with the Uliratha server, reconnecting...");
reconnect();
connected = false;
}else{
Logger.addMessage("We're disconnected from the Uliratha server");
}
}
});
while (true) {
service.selectBlocking();
}
} catch (IOException e) {
if (valid) {
reconnect();
connected = false;
}
}
}
private void reconnect() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
connect();
}
public boolean isConnected() {
return connected;
}
public void disconnect(){
valid = false;
socket.close();
}
private void sendObjects(NIOSocket socket, Object[] objects) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream dataStream = new DataOutputStream(stream);
for (Object o : objects) {
if (o instanceof String) {
dataStream.writeUTF((String) o);
} else if (o instanceof Integer) {
dataStream.writeInt((Integer) o);
} else if (o instanceof byte[]) {
dataStream.write((byte[]) o);
} else if (o instanceof Long) {
dataStream.writeLong((Long) o);
} else if (o instanceof Boolean) {
dataStream.writeBoolean((Boolean) o);
}
}
dataStream.flush();
final byte[] content = stream.toByteArray();
dataStream.close();
socket.write(content);
}
public void sendMessage(String message){
try {
sendObjects(socket, new Object[]{83, message});
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,49 @@
package org.parabot.environment.scripts.uliratha;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.parabot.core.Context;
import org.parabot.environment.api.utils.WebUtil;
import java.io.IOException;
/**
* @author JKetelaar
*/
public class UlirathaExecuter {
private String api;
private static boolean isVip = true;
public UlirathaExecuter(String api){
this.api = api;
}
public void start(int scriptID){
if (UlirathaExecuter.isVip) {
String vipUrl = "http://bdn.parabot.org/api/v2/user/" + api + "/vip";
JSONParser parser = new JSONParser();
try {
JSONObject vipObject = (JSONObject) parser.parse(WebUtil.getReader(vipUrl));
boolean isVip = (boolean) vipObject.get("result");
if (isVip) {
String serverUrl = "http://bdn.parabot.org/api/v2/clients/server";
JSONObject serverObject = (JSONObject) parser.parse(WebUtil.getReader(serverUrl));
JSONObject detailsObject = (JSONObject) serverObject.get("result");
String host = (String) detailsObject.get("host");
long port = (long) detailsObject.get("port");
UlirathaClient client = new UlirathaClient(host, (int) port, scriptID, api);
client.start();
Context.getInstance().setUlirathaClient(client);
}else{
UlirathaExecuter.isVip = false;
}
} catch (IOException | ParseException | ClassCastException e) {
e.printStackTrace();
}
}
}
}
@@ -0,0 +1,50 @@
package org.parabot.environment.servers;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.build.BuildPath;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.servers.executers.ServerExecuter;
import java.net.MalformedURLException;
/**
*
* Loads locally stored server providers
*
* @author Everel
*
*/
public class LocalServerExecuter extends ServerExecuter {
private final ServerProvider serverProvider;
private ClassPath classPath;
private String serverName;
public LocalServerExecuter(ServerProvider serverProvider,
ClassPath classPath, final String serverName) {
this.serverProvider = serverProvider;
this.classPath = classPath;
this.serverName = serverName;
}
@Override
public void run() {
// add jar or directory to buildpath.
if (this.classPath.isJar()) {
Core.verbose("Adding server provider jar to buildpath: "
+ this.classPath.lastParsed.toString());
this.classPath.addToBuildPath();
} else {
Core.verbose("Adding server providers directory to buildpath: "
+ Directories.getServerPath().getPath());
try {
BuildPath.add(Directories.getServerPath().toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
// finalize
super.finalize(this.serverProvider, this.serverName);
}
}
@@ -0,0 +1,22 @@
package org.parabot.environment.servers;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A server manifest
* @author Everel
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ServerManifest {
String author();
String name();
double version();
Type type();
}
@@ -0,0 +1,150 @@
package org.parabot.environment.servers;
import org.objectweb.asm.Opcodes;
import org.parabot.core.Context;
import org.parabot.core.asm.hooks.HookFile;
import org.parabot.core.asm.interfaces.Injectable;
import org.parabot.core.parsers.hooks.HookParser;
import org.parabot.environment.input.Keyboard;
import org.parabot.environment.input.Mouse;
import org.parabot.environment.scripts.Script;
import javax.swing.*;
import java.applet.Applet;
import java.applet.AppletStub;
import java.awt.Dimension;
import java.net.URL;
/**
* Provides a server to the bot
*
* @author Everel
*
*/
public abstract class ServerProvider implements Opcodes {
/**
* Get the game/applet dimensions
* @return game/applet dimensions
*/
public Dimension getGameDimensions() {
return new Dimension(765, 503);
}
/**
* Hooks to parse
*
* @deprecated use getHookFile() now
* @return URL to hooks file
*/
@Deprecated
public URL getHooks() {
return null;
}
/**
* Get hook file to parse
* @return hook file
*/
public HookFile getHookFile() {
return null;
}
/**
* Jar to parse
*
* @return URL to client jar
*/
public abstract URL getJar();
public abstract Applet fetchApplet();
public String getAccessorsPackage() {
return null;
}
public void injectHooks() {
HookFile hookFile = fetchHookFile();
if(hookFile == null) {
return;
}
HookParser parser = hookFile.getParser();
Injectable[] injectables = parser.getInjectables();
if (injectables == null) {
return;
}
for (Injectable inj : injectables) {
inj.inject();
}
Context.getInstance().setHookParser(parser);
}
private HookFile fetchHookFile() {
HookFile hookFile = getHookFile();
if(hookFile != null) {
return hookFile;
}
URL hookLocation = getHooks();
if(hookLocation == null) {
return null;
}
return new HookFile(hookLocation, HookFile.TYPE_XML);
}
/**
* Add custom items to the bot menu bar
*
* @param bar
* menu bar to add items on
*/
public void addMenuItems(JMenuBar bar) {
}
public AppletStub getStub() {
return null;
}
public void setClientInstance(Object client) {
Context.getInstance().setClientInstance(client);
}
public void parseJar() {
Context.getInstance().getClassPath().addJar(getJar());
}
public void initScript(Script script) {
}
public void init() {
}
public void initMouse() {
final Context context = Context.getInstance();
final Applet applet = context.getApplet();
final Mouse mouse = new Mouse(applet);
applet.addMouseListener(mouse);
applet.addMouseMotionListener(mouse);
context.setMouse(mouse);
}
public void initKeyboard() {
final Context context = Context.getInstance();
final Applet applet = context.getApplet();
final Keyboard keyboard = new Keyboard(applet);
applet.addKeyListener(keyboard);
context.setKeyboard(keyboard);
}
public void unloadScript(Script script) {
}
}
@@ -0,0 +1,14 @@
package org.parabot.environment.servers;
/**
*
* Server provider type
*
* @author Everel
*
*/
public enum Type {
INJECTION, REFLECTION, COLOR, LOADER, OTHER
}
@@ -0,0 +1,55 @@
package org.parabot.environment.servers.executers;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.build.BuildPath;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.servers.ServerProvider;
/**
*
* Loads locally stored server providers
*
* @author Everel
*
*/
public class LocalServerExecuter extends ServerExecuter {
private final Constructor<?> serverProviderConstructor;
private ClassPath classPath;
private String serverName;
public LocalServerExecuter(Constructor<?> serverProviderConstructor,
ClassPath classPath, final String serverName) {
this.serverProviderConstructor = serverProviderConstructor;
this.classPath = classPath;
this.serverName = serverName;
}
@Override
public void run() {
// add jar or directory to buildpath.
if (this.classPath.isJar()) {
Core.verbose("Adding server provider jar to buildpath: "
+ this.classPath.lastParsed.toString());
this.classPath.addToBuildPath();
} else {
Core.verbose("Adding server providers directory to buildpath: "
+ Directories.getServerPath().getPath());
try {
BuildPath.add(Directories.getServerPath().toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
// finalize
try {
super.finalize((ServerProvider) serverProviderConstructor.newInstance(), this.serverName);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@@ -0,0 +1,123 @@
package org.parabot.environment.servers.executers;
import org.parabot.core.Configuration;
import org.parabot.core.Context;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.build.BuildPath;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.desc.ServerProviderInfo;
import org.parabot.core.forum.AccountManager;
import org.parabot.core.forum.AccountManagerAccess;
import org.parabot.core.ui.components.VerboseLoader;
import org.parabot.core.ui.utils.UILog;
import org.parabot.environment.api.utils.WebUtil;
import org.parabot.environment.servers.ServerProvider;
import org.parabot.environment.servers.loader.ServerLoader;
import javax.swing.*;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
/**
*
* Fetches a server provider from the Parabot BDN
*
* @author Everel
*
*/
public class PublicServerExecuter extends ServerExecuter {
private String serverName;
private static AccountManager manager;
public static final AccountManagerAccess MANAGER_FETCHER = new AccountManagerAccess() {
@Override
public final void setManager(AccountManager manager) {
PublicServerExecuter.manager = manager;
}
};
public PublicServerExecuter(final String serverName) {
this.serverName = serverName;
}
@Override
public void run() {
try {
ServerProviderInfo serverProviderInfo = new ServerProviderInfo(new URL(Configuration.GET_SERVER_PROVIDER_INFO
+ this.serverName), manager.getAccount().getURLUsername(), manager.getAccount().getURLPassword());
final File destination = new File(Directories.getCachePath(),
serverProviderInfo.getCRC32() + ".jar");
final String jarUrl = Configuration.GET_SERVER_PROVIDER
+ this.serverName;
Core.verbose("Downloading: " + jarUrl + " ...");
if(destination.exists()) {
Core.verbose("Found cached server provider [CRC32: " + serverProviderInfo.getCRC32() + "]");
} else {
WebUtil.downloadFile(new URL(jarUrl), destination,
VerboseLoader.get(), manager.getAccount().getURLUsername(), manager.getAccount().getURLPassword());
Core.verbose("Server provider downloaded...");
}
final ClassPath classPath = new ClassPath();
classPath.addJar(destination);
BuildPath.add(destination.toURI().toURL());
ServerLoader serverLoader = new ServerLoader(classPath);
final String[] classNames = serverLoader.getServerClassNames();
if (classNames == null || classNames.length == 0) {
UILog.log(
"Error",
"Failed to load server provider, error: [No provider found in jar file.]",
JOptionPane.ERROR_MESSAGE);
return;
} else if (classNames.length > 1) {
UILog.log(
"Error",
"Failed to load server provider, error: [Multiple providers found in jar file.]");
return;
}
final String className = classNames[0];
try {
final Class<?> providerClass = serverLoader
.loadClass(className);
final Constructor<?> con = providerClass.getConstructor();
final ServerProvider serverProvider = (ServerProvider) con
.newInstance();
Context.getInstance(serverProvider).setProviderInfo(serverProviderInfo);
super.finalize(serverProvider, this.serverName);
} catch (NoClassDefFoundError | ClassNotFoundException ignored) {
UILog.log(
"Error",
"Failed to load server provider, error: [This server provider is not compitable with this version of parabot]",
JOptionPane.ERROR_MESSAGE);
} catch (Throwable t) {
t.printStackTrace();
UILog.log(
"Error",
"Failed to load server provider, post the stacktrace/error on the parabot forums.",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
UILog.log(
"Error",
"Failed to load server provider, post the stacktrace/error on the parabot forums.",
JOptionPane.ERROR_MESSAGE);
}
}
}
@@ -0,0 +1,35 @@
package org.parabot.environment.servers.executers;
import org.parabot.core.Context;
import org.parabot.core.parsers.randoms.RandomParser;
import org.parabot.core.ui.components.PaintComponent;
import org.parabot.environment.servers.ServerProvider;
/**
*
* Executes a server provider
*
* @author Everel
*
*/
public abstract class ServerExecuter {
public abstract void run();
public void finalize(final ServerProvider provider, final String serverName) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Context context = Context.getInstance(provider);
context.load();
PaintComponent.getInstance().startPainting(context);
RandomParser.enable();
} catch (Throwable t) {
t.printStackTrace();
}
}
}).start();
}
}
@@ -0,0 +1,46 @@
package org.parabot.environment.servers.loader;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.tree.ClassNode;
import org.parabot.core.asm.ASMClassLoader;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.servers.ServerProvider;
/**
*
* An environment to load a server
*
* @author Everel
*
*
*/
public class ServerLoader extends ASMClassLoader {
private ClassPath classPath;
public ServerLoader(ClassPath classPath) {
super(classPath);
this.classPath = classPath;
}
/**
* Gets all classes that extends ServerProvider
* @return string array of class names that extends ServerProvider
*/
public final String[] getServerClassNames() {
final List<String> classNames = new ArrayList<String>();
for (ClassNode c : classPath.classes.values())
if (c.superName.replace('/', '.').equals(
ServerProvider.class.getName())) {
classNames.add(c.name.replace('/', '.'));
}
return classNames.toArray(new String[classNames.size()]);
}
public ClassPath getClassPath() {
return classPath;
}
}