diff --git a/.gitignore b/.gitignore index 1223e80..1050628 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,6 @@ build !.gitmodules !.gitkeep !.gitattributes +lib_managed +doc + diff --git a/GameServer/build.xml b/GameServer/build.xml index c54156b..8f9f763 100644 --- a/GameServer/build.xml +++ b/GameServer/build.xml @@ -1,84 +1,91 @@ - - + + - - + + - - - - + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - + + + - + + + + + + + + + - + + + - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + - + diff --git a/GameServer/conf/world.xml b/GameServer/conf/world.xml index 1ed0064..0c2ffc8 100644 --- a/GameServer/conf/world.xml +++ b/GameServer/conf/world.xml @@ -62,8 +62,8 @@ This uses a LRUMap, and only has a limited number of entries, so only the most active IPs will be stored at a time. --> 5 - + 180000 diff --git a/GameServer/ivy.xml b/GameServer/ivy.xml new file mode 100644 index 0000000..b68035c --- /dev/null +++ b/GameServer/ivy.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/GameServer/lib/bsh.jar b/GameServer/lib/bsh.jar deleted file mode 100644 index 36fe03d..0000000 Binary files a/GameServer/lib/bsh.jar and /dev/null differ diff --git a/GameServer/lib/commons-collections-3.2.1.jar b/GameServer/lib/commons-collections-3.2.1.jar deleted file mode 100644 index c35fa1f..0000000 Binary files a/GameServer/lib/commons-collections-3.2.1.jar and /dev/null differ diff --git a/GameServer/lib/hex-string.jar b/GameServer/lib/hex-string.jar deleted file mode 100644 index 477c6cc..0000000 Binary files a/GameServer/lib/hex-string.jar and /dev/null differ diff --git a/GameServer/lib/mail.jar b/GameServer/lib/mail.jar deleted file mode 100644 index d1a4971..0000000 Binary files a/GameServer/lib/mail.jar and /dev/null differ diff --git a/GameServer/lib/mysql-connector.jar b/GameServer/lib/mysql-connector.jar deleted file mode 100644 index 4741577..0000000 Binary files a/GameServer/lib/mysql-connector.jar and /dev/null differ diff --git a/GameServer/lib/scala-compiler.jar b/GameServer/lib/scala-compiler.jar deleted file mode 100644 index 1ed0ba0..0000000 Binary files a/GameServer/lib/scala-compiler.jar and /dev/null differ diff --git a/GameServer/lib/scala-library.jar b/GameServer/lib/scala-library.jar deleted file mode 100644 index 6d4a53c..0000000 Binary files a/GameServer/lib/scala-library.jar and /dev/null differ diff --git a/GameServer/lib/slf4j.jar b/GameServer/lib/slf4j.jar deleted file mode 100644 index c78cb25..0000000 Binary files a/GameServer/lib/slf4j.jar and /dev/null differ diff --git a/GameServer/src/org/moparscape/msc/gs/Server.java b/GameServer/src/org/moparscape/msc/gs/Server.java index 342d396..7c81ae3 100644 --- a/GameServer/src/org/moparscape/msc/gs/Server.java +++ b/GameServer/src/org/moparscape/msc/gs/Server.java @@ -37,9 +37,16 @@ public class Server { File f = new File(args[0]); if (f.exists()) { configFile = f.getName(); + } else { + System.out.println("Config not found: " + f.getCanonicalPath()); + displayConfigDefaulting(configFile); } + } else { + System.out.println("No config file specified."); + displayConfigDefaulting(configFile); } + Config.initConfig(configFile); world = Instance.getWorld(); world.wl.loadObjects(); @@ -157,7 +164,12 @@ public class Server { acceptor.bind(new InetSocketAddress(Config.SERVER_IP, Config.SERVER_PORT), new RSCConnectionHandler(engine), config); - + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + acceptor.unbindAll(); + } + }); } catch (Exception e) { Logger.error(e); } @@ -235,4 +247,8 @@ public class Server { public static Server getServer() { return server; } + + private static void displayConfigDefaulting(String file) { + System.out.println("Defaulting to use " + file); + } } diff --git a/GameServer/src/org/moparscape/msc/gs/core/ClientUpdater.java b/GameServer/src/org/moparscape/msc/gs/core/ClientUpdater.java index 58c2846..70a01c1 100644 --- a/GameServer/src/org/moparscape/msc/gs/core/ClientUpdater.java +++ b/GameServer/src/org/moparscape/msc/gs/core/ClientUpdater.java @@ -20,10 +20,8 @@ import org.moparscape.msc.gs.model.snapshot.Chatlog; import org.moparscape.msc.gs.tools.DataConversions; import org.moparscape.msc.gs.util.EntityList; import org.moparscape.msc.gs.util.Logger; -import org.moparscape.msc.gs.util.Processor; -import org.moparscape.msc.gs.util.WorkGroup; -public final class ClientUpdater implements Processor { +public final class ClientUpdater { public static int pktcount = 0; private static World world = Instance.getWorld(); @@ -37,11 +35,9 @@ public final class ClientUpdater implements Processor { private WallObjectPositionPacketBuilder wallObjectPositionPacketBuilder = new WallObjectPositionPacketBuilder(); private EntityList players = world.getPlayers(); - private WorkGroup clientInformerGroup = null; public ClientUpdater() { world.setClientUpdater(this); - this.clientInformerGroup = new WorkGroup(this); } /** @@ -134,30 +130,22 @@ public final class ClientUpdater implements Processor { updateOffers(); - if (threaded) { - try { - clientInformerGroup.processWorkload(players); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - } else { - for (Player p : players) { - // Logging.debug("Process for player " + p.getUsername() + - // " | threaded: " + threaded); + for (Player p : players) { + // Logging.debug("Process for player " + p.getUsername() + + // " | threaded: " + threaded); - updateTimeouts(p); + updateTimeouts(p); - updatePlayerPositions(p); - updateNpcPositions(p); - updateGameObjects(p); - updateWallObjects(p); - updateItems(p); + updatePlayerPositions(p); + updateNpcPositions(p); + updateGameObjects(p); + updateWallObjects(p); + updateItems(p); - p.setFirstMajorUpdateSent(true); + p.setFirstMajorUpdateSent(true); - } - updateCollections(); } + updateCollections(); } public void process(Player p) { diff --git a/GameServer/src/org/moparscape/msc/gs/core/GameEngine.java b/GameServer/src/org/moparscape/msc/gs/core/GameEngine.java index 78a2bb8..366f056 100644 --- a/GameServer/src/org/moparscape/msc/gs/core/GameEngine.java +++ b/GameServer/src/org/moparscape/msc/gs/core/GameEngine.java @@ -328,40 +328,39 @@ public final class GameEngine extends Thread { Thread.sleep(50); } catch (InterruptedException ie) { } - time = System.currentTimeMillis(); - long Delay; + long deltaTime = updateTime(); processLoginServer(); - Delay = System.currentTimeMillis() - time; - if (Delay >= 1000) + if ((deltaTime = getDeltaTime()) >= 1000) Logger.println("processLoginServer is taking longer than it should, exactly " - + Delay + "ms"); - time = System.currentTimeMillis(); + + deltaTime + "ms"); processIncomingPackets(); - Delay = System.currentTimeMillis() - time; - if (Delay >= 1000) + if ((deltaTime = getDeltaTime()) >= 1000) Logger.println("processIncomingPackets is taking longer than it should, exactly " - + Delay + "ms"); - time = System.currentTimeMillis(); + + deltaTime + "ms"); processEvents(); - Delay = System.currentTimeMillis() - time; - if (Delay >= 1000) + if ((deltaTime = getDeltaTime()) >= 1000) Logger.println("processEvents is taking longer than it should, exactly " - + Delay + "ms"); - time = System.currentTimeMillis(); + + deltaTime + "ms"); processClients(); - Delay = System.currentTimeMillis() - time; - if (Delay >= 1000) + if ((deltaTime = getDeltaTime()) >= 1000) Logger.println("processClients is taking longer than it should, exactly " - + Delay + "ms"); - time = System.currentTimeMillis(); + + deltaTime + "ms"); cleanSnapshotDeque(); - Delay = System.currentTimeMillis() - time; - if (Delay >= 1000) + if ((deltaTime = getDeltaTime()) >= 1000) Logger.println("processSnapshotDeque is taking longer than it should, exactly " - + Delay + "ms"); + + deltaTime + "ms"); } } + public long getDeltaTime() { + long t1 = time; + return updateTime() - t1; + } + + public long updateTime() { + return time = System.currentTimeMillis(); + } + /** * Cleans snapshots of entries over 60 seconds old (executed every second) */ diff --git a/GameServer/src/org/moparscape/msc/gs/core/LoginConnector.java b/GameServer/src/org/moparscape/msc/gs/core/LoginConnector.java index c27df9b..ff7a630 100644 --- a/GameServer/src/org/moparscape/msc/gs/core/LoginConnector.java +++ b/GameServer/src/org/moparscape/msc/gs/core/LoginConnector.java @@ -200,6 +200,9 @@ public class LoginConnector { + connectionAttempts + " tries"); System.exit(1); return false; + } else { + // Add a delay so it doesn't instantly get to 100 + Thread.sleep(1000); } return reconnect(); diff --git a/GameServer/src/org/moparscape/msc/gs/model/Player.java b/GameServer/src/org/moparscape/msc/gs/model/Player.java index 00bc03b..2d4230d 100644 --- a/GameServer/src/org/moparscape/msc/gs/model/Player.java +++ b/GameServer/src/org/moparscape/msc/gs/model/Player.java @@ -532,6 +532,65 @@ public final class Player extends Mob { private int[] wornItems = new int[12]; private int wrongwords = 0; + private int poisonPower = 0; + private DelayedEvent poisonEvent; + + public boolean isPoisoned() { + return poisonPower > 0; + } + + public void poison(int power) { + if (!isPoisoned()) { + this.poisonPower = power; + poisonEvent = new DelayedEvent(this, 19500) { + public void run() { + damagePoison(true); + } + }; + World.getWorld().getDelayedEventHandler().add(poisonEvent); + } else + this.poisonPower = power; + } + + public void curePoison() { + this.poisonPower = 0; + if (poisonEvent != null) + poisonEvent.stop(); + } + + public void startPoison(int power) { + this.poison(power); + this.poisonPower = power; + + damagePoison(false); + } + + public void damagePoison(boolean decrease) { + if (this.poisonPower > 0) { + double calcDamage = Math.ceil(poisonPower / 5); + int damage = (int) calcDamage + 1; + + if (decrease) + poisonPower--; + + setLastDamage(damage); + setCurStat(3, getCurStat(3) - damage); + getActionSender().sendStat(3); + getActionSender().sendMessage( + "@gr3@You @gr2@are @gr1@Poisoned! @gr2@You @gr3@lose " + + damage + " @gr1@health."); + + for (Player p : getViewArea().getPlayersInView()) + p.informOfModifiedHits(this); + if (getCurStat(3) <= 0) + killedBy(null, false); + } else { + if (poisonEvent != null) + poisonEvent.stop(); + this.poisonPower = 0; + } + } + public Player(IoSession ios) { ioSession = ios; @@ -586,9 +645,11 @@ public final class Player extends Mob { /** * This method acts as a throttle for packets, and adds them to a list.
- * If the player sends more than 20 packets per second they're disconnected (60 packets per 3000ms) + * If the player sends more than 20 packets per second they're disconnected + * (60 packets per 3000ms) * - * @param p - the packet to add... + * @param p + * - the packet to add... */ public void addPacket(RSCPacket p) { long now = GameEngine.getTime(); @@ -660,13 +721,14 @@ public final class Player extends Mob { if (this != null && this.location != null && this.location.inWilderness()) { if (GameEngine.getTime() - this.getLastMoved() < Config.WILD_STAND_STILL_TIME) { - getActionSender() - .sendMessage( - "You must stand peacefully in one place for " + Config.WILD_STAND_STILL_TIME + " seconds!"); + getActionSender().sendMessage( + "You must stand peacefully in one place for " + + Config.WILD_STAND_STILL_TIME + " seconds!"); return false; } } - return !isBusy() && GameEngine.getTime() - getCombatTimer() > Config.WILD_STAND_STILL_TIME; + return !isBusy() + && GameEngine.getTime() - getCombatTimer() > Config.WILD_STAND_STILL_TIME; } public boolean canReport() { @@ -1618,7 +1680,8 @@ public final class Player extends Mob { if (getLocation().wildernessLevel() > 1) { if (combat) exprate += Config.WILD_COMBAT_BONUS; - if (getLocation().wildernessLevel() > Config.WILD_LEVEL_FOR_NON_COMBAT_BONUS && !combat) + if (getLocation().wildernessLevel() > Config.WILD_LEVEL_FOR_NON_COMBAT_BONUS + && !combat) exprate += Config.WILD_NON_COMBAT_BONUS; } diff --git a/GameServer/src/org/moparscape/msc/gs/tools/DataConversions.java b/GameServer/src/org/moparscape/msc/gs/tools/DataConversions.java index 0e8a43a..1e8cffe 100644 --- a/GameServer/src/org/moparscape/msc/gs/tools/DataConversions.java +++ b/GameServer/src/org/moparscape/msc/gs/tools/DataConversions.java @@ -12,10 +12,9 @@ import java.util.Random; import org.moparscape.msc.gs.connection.RSCPacket; import org.moparscape.msc.gs.core.GameEngine; import org.moparscape.msc.gs.model.Point; +import org.moparscape.msc.gs.util.HexString; import org.moparscape.msc.gs.util.Logger; -import com.bombaydigital.vault.HexString; - public final class DataConversions { private static char characters[] = { ' ', 'e', 't', 'a', 'o', 'i', 'h', 'n', 's', 'r', 'd', 'l', 'u', 'm', 'w', 'c', 'y', 'f', 'g', 'p', @@ -261,7 +260,7 @@ public final class DataConversions { public static String md5(String s) { md.reset(); md.update(s.getBytes()); - return HexString.bufferToHex(md.digest()); + return new HexString(md.digest()).toString(); } /** diff --git a/GameServer/src/org/moparscape/msc/gs/util/DelayMonitor.java b/GameServer/src/org/moparscape/msc/gs/util/DelayMonitor.java deleted file mode 100644 index 131e26a..0000000 --- a/GameServer/src/org/moparscape/msc/gs/util/DelayMonitor.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.moparscape.msc.gs.util; - -import java.text.DecimalFormat; - -public class DelayMonitor { - private static final DecimalFormat formatter = new DecimalFormat( - "###,###.###"); - private long t, t1, t2; - private int totalItemsUpdated; - private int numRepeats; - - public void startMeasuring() { - t1 = System.nanoTime(); - } - - public void setItemsUpdated(int i) { - totalItemsUpdated += i; - } - - public void endMeasuring() { - t2 = System.nanoTime(); - processMeasurements(); - } - - public double getAvgDelay() { - return (t / numRepeats) / 1e6; - } - - public double getAvgItemsPerRepeat() { - return (totalItemsUpdated / numRepeats); - } - - public int getRepeatCount() { - return numRepeats; - } - - public void reset() { - t = t1 = t2 = numRepeats = totalItemsUpdated = 0; - } - - private void processMeasurements() { - t += (t2 - t1); - numRepeats++; - } - - public static String toString(double d) { - return formatter.format(d); - } -} diff --git a/GameServer/src/org/moparscape/msc/gs/util/HexString.scala b/GameServer/src/org/moparscape/msc/gs/util/HexString.scala new file mode 100644 index 0000000..6b73e25 --- /dev/null +++ b/GameServer/src/org/moparscape/msc/gs/util/HexString.scala @@ -0,0 +1,7 @@ +package org.moparscape.msc.gs.util + +class HexString(bytes: Array[Byte]) { + lazy val string = bytes.map(0xFF & _).map { "%02x".format(_) }.foldLeft("") { _ + _ } + + override def toString = string +} \ No newline at end of file diff --git a/GameServer/src/org/moparscape/msc/gs/util/Processor.java b/GameServer/src/org/moparscape/msc/gs/util/Processor.java deleted file mode 100644 index 23a1268..0000000 --- a/GameServer/src/org/moparscape/msc/gs/util/Processor.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.moparscape.msc.gs.util; - -import org.moparscape.msc.gs.model.Player; - -public interface Processor { - public void process(Player p); -} diff --git a/GameServer/src/org/moparscape/msc/gs/util/WorkGroup.java b/GameServer/src/org/moparscape/msc/gs/util/WorkGroup.java deleted file mode 100644 index 9afcbf7..0000000 --- a/GameServer/src/org/moparscape/msc/gs/util/WorkGroup.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.moparscape.msc.gs.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; - -import org.moparscape.msc.gs.core.ClientUpdater; -import org.moparscape.msc.gs.model.Player; - -/** - * This class manages a set of Workers. - */ -public class WorkGroup { - private List uncaughtExceptions; - private Worker[] workers; - private Thread[] workerThreads; - private BlockingQueue workload = null; - private Processor processor; - - public WorkGroup(Processor p) { - this(p, Runtime.getRuntime().availableProcessors() + 1); - } - - /** - * Start the workgroup. All threads are initiated into a sleeping state. - */ - public WorkGroup(Processor p, int numWorkers) { - this.workload = new ArrayBlockingQueue(1000); - this.processor = p; - this.workers = new Worker[numWorkers]; - this.uncaughtExceptions = new ArrayList(); - workerThreads = new Thread[workers.length]; - for (int i = 0; i < workers.length; i++) { - workers[i] = new Worker(this, workload, processor); - workerThreads[i] = new Thread(workers[i], "-" + i); - workerThreads[i].start(); - } - } - - public void processWorkload(Collection players) - throws InterruptedException { - uncaughtExceptions.clear(); - setWorkload(players); - waitFor(); - } - - public boolean shouldProcess() { - return !((ClientUpdater) processor).updatingCollections; - } - - private void waitFor() throws InterruptedException { - while (!workload.isEmpty()) - Thread.sleep(10); - - ((ClientUpdater) processor).updateCollections(); - } - - public int remainingJobs() { - return workload.size(); - } - - public int getNumWorkers() { - return workers.length; - } - - public void addUncaughtException(Throwable t) { - t.printStackTrace(); - uncaughtExceptions.add(t); - } - - public void setWorkload(Collection c) { - workload.clear(); - workload.addAll(c); - } -} diff --git a/GameServer/src/org/moparscape/msc/gs/util/Worker.java b/GameServer/src/org/moparscape/msc/gs/util/Worker.java deleted file mode 100644 index 1af4425..0000000 --- a/GameServer/src/org/moparscape/msc/gs/util/Worker.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.moparscape.msc.gs.util; - -import java.util.concurrent.BlockingQueue; - -import org.moparscape.msc.gs.model.Player; - -/** - * The Worker class is a runnable class that can be used for splitting up a - * workload into multiple Workers. This class should only ever be used through a - * WorkGroup. - */ -public class Worker implements Runnable { - private WorkGroup parent; - private BlockingQueue workload; - private Processor processor; - private boolean running = true; - - public Worker(WorkGroup wg, BlockingQueue workload, Processor p) { - this.parent = wg; - this.workload = workload; - this.processor = p; - } - - public void stop() { - running = false; - } - - public void run() { - while (running) { - try { - if (parent.shouldProcess()) { - Player element = workload.take(); - processor.process(element); - } - } catch (InterruptedException ie) { - // thread has been asked to stop - running = false; - } catch (Exception e) { - parent.addUncaughtException(e); - } - } - } -} diff --git a/LoginServer/build.xml b/LoginServer/build.xml index f2edc14..918f4d7 100644 --- a/LoginServer/build.xml +++ b/LoginServer/build.xml @@ -4,7 +4,6 @@ - @@ -29,20 +28,17 @@ - - - - - + + - + diff --git a/LoginServer/ls.conf b/LoginServer/conf/Config.xml similarity index 86% rename from LoginServer/ls.conf rename to LoginServer/conf/Config.xml index 35effc0..2cbceba 100644 --- a/LoginServer/ls.conf +++ b/LoginServer/conf/Config.xml @@ -11,4 +11,5 @@ localhost 8186 http://localhost/auth.php + org.moparscape.msc.ls.persistence.impl.MySQL diff --git a/LoginServer/src/org/moparscape/msc/ls/LoginEngine.java b/LoginServer/src/org/moparscape/msc/ls/LoginEngine.java index d88127d..13190e5 100644 --- a/LoginServer/src/org/moparscape/msc/ls/LoginEngine.java +++ b/LoginServer/src/org/moparscape/msc/ls/LoginEngine.java @@ -106,7 +106,7 @@ public class LoginEngine extends Thread { handler.handlePacket(p, p.getSession()); uniqueHandlers.remove(p.getUID()); } catch (Exception e) { - Server.error("Exception with p[" + p.getID() + "]: " + e); + e.printStackTrace(); } } else { Server.error("Unhandled packet from server: " + p.getID()); @@ -118,7 +118,7 @@ public class LoginEngine extends Thread { try { handler.handlePacket(p, p.getSession()); } catch (Exception e) { - Server.error("Exception with p[" + p.getID() + "]: " + e); + e.printStackTrace(); } } else { Server.error("Unhandled packet from frontend: " + p.getID()); diff --git a/LoginServer/src/org/moparscape/msc/ls/Server.java b/LoginServer/src/org/moparscape/msc/ls/Server.java index 12fc7e8..5910e55 100644 --- a/LoginServer/src/org/moparscape/msc/ls/Server.java +++ b/LoginServer/src/org/moparscape/msc/ls/Server.java @@ -14,184 +14,206 @@ import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; import org.apache.mina.transport.socket.nio.SocketSessionConfig; import org.moparscape.msc.ls.model.PlayerSave; import org.moparscape.msc.ls.model.World; -import org.moparscape.msc.ls.net.DatabaseConnection; import org.moparscape.msc.ls.net.FConnectionHandler; import org.moparscape.msc.ls.net.LSConnectionHandler; +import org.moparscape.msc.ls.persistence.StorageMedium; +import org.moparscape.msc.ls.persistence.StorageMediumFactory; import org.moparscape.msc.ls.util.Config; - public class Server { - /** - * Connection to the MySQL database - */ - public static DatabaseConnection db; - private static Server server; + public static StorageMedium storage; + private static Server server; - public static void error(Object o) { - if (o instanceof Exception) { - Exception e = (Exception) o; - e.printStackTrace(); - System.exit(1); - return;// Adding save data + public static void error(Object o) { + if (o instanceof Exception) { + Exception e = (Exception) o; + e.printStackTrace(); + System.exit(1); + return;// Adding save data + } + System.err.println(o.toString()); } - System.err.println(o.toString()); - } - public static Server getServer() { - if (server == null) { - server = new Server(); + public static Server getServer() { + if (server == null) { + server = new Server(); + } + return server; } - return server; - } - public static void main(String[] args) throws IOException { - String configFile = "conf/ls/Conf.xml"; - if (args.length > 0) { - File f = new File(args[0]); - if (f.exists()) { - configFile = f.getName(); - } + public static void main(String[] args) throws IOException { + String configFile = "conf" + File.separator + "Config.xml"; + if (args.length > 0) { + File f = new File(args[0]); + if (f.exists()) { + configFile = f.getName(); + } else { + System.out.println("Config not found: " + f.getCanonicalPath()); + displayConfigDefaulting(configFile); + } + } else { + System.out.println("No config file specified."); + displayConfigDefaulting(configFile); + } + System.out.println("Login Server starting up..."); + Config.initConfig(configFile); + try { + storage = StorageMediumFactory.createMedium(Config.STORAGE_MEDIUM); + } catch (Exception e) { + e.printStackTrace(); + return; + } + System.out.println("Storage Medium: " + + storage.getClass().getSimpleName()); + Server.getServer(); } - System.out.println("Login Server starting up..."); - Config.initConfig(configFile); - db = new DatabaseConnection(); - System.out.println("Connected to MySQL"); - Server.getServer(); - } - /** - * The login engine - */ - private LoginEngine engine; - /** - * The Server SocketAcceptor - */ - private IoAcceptor frontendAcceptor; + /** + * The login engine + */ + private LoginEngine engine; + /** + * The Server SocketAcceptor + */ + private IoAcceptor frontendAcceptor; - private TreeMap idleWorlds = new TreeMap(); + private TreeMap idleWorlds = new TreeMap(); - /** - * The Server SocketAcceptor - */ - private IoAcceptor serverAcceptor; + /** + * The Server SocketAcceptor + */ + private IoAcceptor serverAcceptor; - private TreeMap worlds = new TreeMap(); + private TreeMap worlds = new TreeMap(); - private Server() { - try { - engine = new LoginEngine(this); - engine.start(); - serverAcceptor = createListener(Config.LS_IP, Config.LS_PORT, new LSConnectionHandler(engine)); - frontendAcceptor = createListener(Config.QUERY_IP, Config.QUERY_PORT, new FConnectionHandler(engine)); - } catch (IOException e) { - Server.error(e); + private Server() { + try { + engine = new LoginEngine(this); + engine.start(); + serverAcceptor = createListener(Config.LS_IP, Config.LS_PORT, + new LSConnectionHandler(engine)); + frontendAcceptor = createListener(Config.QUERY_IP, + Config.QUERY_PORT, new FConnectionHandler(engine)); + } catch (IOException e) { + Server.error(e); + } } - } - private IoAcceptor createListener(String ip, int port, IoHandler handler) throws IOException { - IoAcceptor acceptor = new SocketAcceptor(); - IoAcceptorConfig config = new SocketAcceptorConfig(); - config.setDisconnectOnUnbind(true); - ((SocketSessionConfig) config.getSessionConfig()).setReuseAddress(true); - acceptor.bind(new InetSocketAddress(ip, port), handler, config); - return acceptor; - } - - public PlayerSave findSave(long user, World world) { - PlayerSave save = null; - // for(World w : getWorlds()) { - // PlayerSave s = w.getSave(user); - // if(s != null) { - // w.unassosiateSave(s); - // save = s; - // Logging.debug("Found cached save for " + - // DataConversions.hashToUsername(user)); - // break; - // } - // } - // if(save == null) { - // Logging.debug("No save found for " + - // DataConversions.hashToUsername(user) + ", loading fresh"); - save = PlayerSave.loadPlayer(user); - // } - // world.assosiateSave(save); - return save; - } - - public World findWorld(long user) { - for (World w : getWorlds()) { - if (w.hasPlayer(user)) { - return w; - } + private IoAcceptor createListener(String ip, int port, IoHandler handler) + throws IOException { + final IoAcceptor acceptor = new SocketAcceptor(); + IoAcceptorConfig config = new SocketAcceptorConfig(); + config.setDisconnectOnUnbind(true); + ((SocketSessionConfig) config.getSessionConfig()).setReuseAddress(true); + acceptor.bind(new InetSocketAddress(ip, port), handler, config); + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + acceptor.unbindAll(); + } + }); + return acceptor; } - return null; - } - public LoginEngine getEngine() { - return engine; - } - - public World getIdleWorld(int id) { - return idleWorlds.get(id); - } - - public World getWorld(int id) { - if (id < 0) { - return null; + public PlayerSave findSave(long user, World world) { + PlayerSave save = null; + // for(World w : getWorlds()) { + // PlayerSave s = w.getSave(user); + // if(s != null) { + // w.unassosiateSave(s); + // save = s; + // Logging.debug("Found cached save for " + + // DataConversions.hashToUsername(user)); + // break; + // } + // } + // if(save == null) { + // Logging.debug("No save found for " + + // DataConversions.hashToUsername(user) + ", loading fresh"); + save = PlayerSave.loadPlayer(user); + // } + // world.assosiateSave(save); + return save; } - return worlds.get(id); - } - public Collection getWorlds() { - return worlds.values(); - } + public World findWorld(long user) { + for (World w : getWorlds()) { + if (w.hasPlayer(user)) { + return w; + } + } + return null; + } - public boolean isRegistered(World world) { - return getWorld(world.getID()) != null; - } + public LoginEngine getEngine() { + return engine; + } - public void kill() { - try { - serverAcceptor.unbindAll(); - frontendAcceptor.unbindAll(); - db.close(); - } catch (Exception e) { - Server.error(e); + public World getIdleWorld(int id) { + return idleWorlds.get(id); } - } - public boolean registerWorld(World world) { - int id = world.getID(); - if (id < 0 || getWorld(id) != null) { - return false; + public World getWorld(int id) { + if (id < 0) { + return null; + } + return worlds.get(id); } - worlds.put(id, world); - return true; - } - public void setIdle(World world, boolean idle) { - if (idle) { - worlds.remove(world.getID()); - idleWorlds.put(world.getID(), world); - } else { - idleWorlds.remove(world.getID()); - worlds.put(world.getID(), world); + public Collection getWorlds() { + return worlds.values(); } - } - public boolean unregisterWorld(World world) { - int id = world.getID(); - if (id < 0) { - return false; + public boolean isRegistered(World world) { + return getWorld(world.getID()) != null; } - if (getWorld(id) != null) { - worlds.remove(id); - return true; + + public void kill() { + try { + serverAcceptor.unbindAll(); + frontendAcceptor.unbindAll(); + storage.shutdown(); + } catch (Exception e) { + Server.error(e); + } } - if (getIdleWorld(id) != null) { - idleWorlds.remove(id); - return true; + + public boolean registerWorld(World world) { + int id = world.getID(); + if (id < 0 || getWorld(id) != null) { + return false; + } + worlds.put(id, world); + return true; + } + + public void setIdle(World world, boolean idle) { + if (idle) { + worlds.remove(world.getID()); + idleWorlds.put(world.getID(), world); + } else { + idleWorlds.remove(world.getID()); + worlds.put(world.getID(), world); + } + } + + public boolean unregisterWorld(World world) { + int id = world.getID(); + if (id < 0) { + return false; + } + if (getWorld(id) != null) { + worlds.remove(id); + return true; + } + if (getIdleWorld(id) != null) { + idleWorlds.remove(id); + return true; + } + return false; + } + + private static void displayConfigDefaulting(String file) { + System.out.println("Defaulting to use " + file); } - return false; - } } \ No newline at end of file diff --git a/LoginServer/src/org/moparscape/msc/ls/model/PlayerSave.java b/LoginServer/src/org/moparscape/msc/ls/model/PlayerSave.java index 5005f2c..cc323e1 100644 --- a/LoginServer/src/org/moparscape/msc/ls/model/PlayerSave.java +++ b/LoginServer/src/org/moparscape/msc/ls/model/PlayerSave.java @@ -1,136 +1,16 @@ package org.moparscape.msc.ls.model; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.util.DataConversions; public class PlayerSave { - public static final String[] statArray = { "attack", "defense", "strength", - "hits", "ranged", "prayer", "magic", "cooking", "woodcut", - "fletching", "fishing", "firemaking", "crafting", "smithing", - "mining", "herblaw", "agility", "thieving" }; public static PlayerSave loadPlayer(long user) { - PlayerSave save = new PlayerSave(user); - ResultSet result; - - try { - result = Server.db - .getQuery("SELECT * FROM `pk_players` WHERE `user`='" - + save.getUser() + "'"); - if (!result.next()) { - return save; - } - - long eventcd = result.getLong("eventcd"); - long subexp = result.getLong("sub_expires"); - @SuppressWarnings("unused") - long now = System.currentTimeMillis() / 1000; - int sowner = result.getInt("owner"); - save.setOwner(sowner, result.getInt("group_id"), subexp); - save.setMuted(result.getLong("muted")); - /* - * if(subexp - now < 1) { - * Server.db.updateQuery("UPDATE users SET group_id='4' WHERE `id`='" - * + sowner + "'"); save.setOwner(sowner, 0, - * result.getLong("subexp")); } - */ - - save.setLogin(result.getLong("login_date"), - DataConversions.IPToLong(result.getString("login_ip"))); - save.setLocation(result.getInt("x"), result.getInt("y")); - - save.setFatigue(result.getInt("fatigue")); - save.setCombatStyle((byte) result.getInt("combatstyle")); - - save.setPrivacy(result.getInt("block_chat") == 1, - result.getInt("block_private") == 1, - result.getInt("block_trade") == 1, - result.getInt("block_duel") == 1); - save.setSettings(result.getInt("cameraauto") == 1, - result.getInt("onemouse") == 1, - result.getInt("soundoff") == 1, - result.getInt("showroof") == 1, - result.getInt("autoscreenshot") == 1, - result.getInt("combatwindow") == 1); - - save.setAppearance((byte) result.getInt("haircolour"), - (byte) result.getInt("topcolour"), - (byte) result.getInt("trousercolour"), - (byte) result.getInt("skincolour"), - (byte) result.getInt("headsprite"), - (byte) result.getInt("bodysprite"), - result.getInt("male") == 1, result.getInt("skulled")); - - save.setQuestPoints(result.getInt("quest_points")); - - result = Server.db - .getQuery("SELECT * FROM `pk_experience` WHERE `user`='" - + save.getUser() + "'"); - if (!result.next()) { - return save; - } - for (int i = 0; i < 18; i++) { - save.setExp(i, result.getInt("exp_" + statArray[i])); - } - - result = Server.db - .getQuery("SELECT * FROM `pk_curstats` WHERE `user`='" - + save.getUser() + "'"); - if (!result.next()) { - return save; - } - for (int i = 0; i < 18; i++) { - save.setLvl(i, result.getInt("cur_" + statArray[i])); - } - - result = Server.db - .getQuery("SELECT id,amount,wielded FROM `pk_invitems` WHERE `user`='" - + save.getUser() + "' ORDER BY `slot` ASC"); - while (result.next()) { - save.addInvItem(result.getInt("id"), result.getInt("amount"), - result.getInt("wielded") == 1); - } - - result = Server.db - .getQuery("SELECT id,amount FROM `pk_bank` WHERE `user`='" - + save.getUser() + "' ORDER BY `slot` ASC"); - while (result.next()) { - save.addBankItem(result.getInt("id"), result.getInt("amount")); - } - - result = Server.db - .getQuery("SELECT friend FROM `pk_friends` WHERE `user`='" - + save.getUser() + "'"); - while (result.next()) { - save.addFriend(result.getLong("friend")); - } - - result = Server.db - .getQuery("SELECT `ignore` FROM `pk_ignores` WHERE `user`='" - + save.getUser() + "'"); - while (result.next()) { - save.addIgnore(result.getLong("ignore")); - } - result = Server.db - .getQuery("SELECT * FROM `pk_quests` WHERE `user`='" - + save.getUser() + "'"); - while (result.next()) { - save.setQuestStage(result.getInt("id"), result.getInt("stage")); - } - save.setEventCD(eventcd); - - } catch (SQLException e) { - Server.error("SQL Exception Loading " - + DataConversions.hashToUsername(user) + ": " - + e.getMessage()); - } - - return save; + return Server.storage.loadPlayer(user); } private long eventcd = 0; @@ -141,7 +21,7 @@ public class PlayerSave { combatWindow; private int combat, skillTotal; private byte combatStyle; - private long[] exp = new long[18]; + private int[] exp = new int[18]; private int fatigue; private ArrayList friendList = new ArrayList(); private byte hairColour, topColour, trouserColour, skinColour, headSprite, @@ -162,7 +42,7 @@ public class PlayerSave { private int x, y; - private PlayerSave(long user) { + public PlayerSave(long user) { this.user = user; } @@ -173,10 +53,16 @@ public class PlayerSave { public void addFriend(long friend) { friendList.add(friend); } - + + public void addFriends(List friends) { + friendList.addAll(friends); + } public void addIgnore(long friend) { ignoreList.add(friend); } + public void addIgnore(List ignored) { + ignoreList.addAll(ignored); + } public void addInvItem(int id, int amount, boolean wielded) { invItems.add(new InvItem(id, amount, wielded)); @@ -229,6 +115,10 @@ public class PlayerSave { public BankItem getBankItem(int i) { return bankItems.get(i); } + + public List getBankItems() { + return bankItems; + } public int getBodySprite() { return bodySprite; @@ -367,86 +257,7 @@ public class PlayerSave { } public boolean save() { - try { - String query; - - Server.db.updateQuery("DELETE FROM `pk_bank` WHERE `user`='" + user - + "'"); - if (bankItems.size() > 0) { - query = "INSERT INTO `pk_bank`(`user`, `id`, `amount`, `slot`) VALUES"; - int slot = 0; - for (BankItem item : bankItems) { - query += "('" + user + "', '" + item.getID() + "', '" - + item.getAmount() + "', '" + (slot++) + "'),"; - } - Server.db.updateQuery(query.substring(0, query.length() - 1)); - } - - Server.db.updateQuery("DELETE FROM `pk_invitems` WHERE `user`='" - + user + "'"); - - ResultSet result = Server.db - .getQuery("Select 1 FROM `pk_players` WHERE `user`='" - + user + "' AND `owner`='" + owner + "'"); - if (!result.next()) - return false; - - Server.db.updateQuery("UPDATE `pk_players` SET `combat`=" + combat - + ", skill_total=" + skillTotal + ", `x`=" + x + ", `y`='" - + y + "', `fatigue`='" + fatigue + "', `haircolour`=" - + hairColour + ", `topcolour`=" + topColour - + ", `trousercolour`=" + trouserColour + ", `skincolour`=" - + skinColour + ", `headsprite`=" + headSprite - + ", `bodysprite`=" + bodySprite + ", `male`=" - + (male ? 1 : 0) + ", `skulled`=" + skulled - + ", `combatstyle`=" + combatStyle + ", `quest_points`=" - + questPoints + " WHERE `user`='" + user + "'"); - - query = "UPDATE `pk_experience` SET "; - for (int i = 0; i < 18; i++) - query += "`exp_" + statArray[i] + "`=" + exp[i] + ","; - - Server.db.updateQuery(query.substring(0, query.length() - 1) - + " WHERE `user`='" + user + "'"); - - query = "UPDATE `pk_curstats` SET "; - for (int i = 0; i < 18; i++) - query += "`cur_" + statArray[i] + "`=" + lvl[i] + ","; - - Server.db.updateQuery(query.substring(0, query.length() - 1) - + " WHERE `user`='" + user + "'"); - - if (invItems.size() > 0) { - query = "INSERT INTO `pk_invitems`(`user`, `id`, `amount`, `wielded`, `slot`) VALUES"; - int slot = 0; - for (InvItem item : invItems) - query += "('" + user + "', '" + item.getID() + "', '" - + item.getAmount() + "', '" - + (item.isWielded() ? 1 : 0) + "', '" + (slot++) - + "'),"; - - Server.db.updateQuery(query.substring(0, query.length() - 1)); - } - - Server.db.updateQuery("DELETE FROM `pk_quests` WHERE `user`='" - + user + "'"); - query = "INSERT INTO `pk_quests` (`user`, `id`, `stage`) VALUES"; - java.util.Set keys = questStage.keySet(); - for (int id : keys) - query += "('" + user + "', '" + id + "', '" - + questStage.get(id) + "'),"; - - Server.db.updateQuery(query.substring(0, query.length() - 1)); - - Server.db.updateQuery("UPDATE `pk_players` SET eventcd='" - + getEventCD() + "' WHERE user='" + user + "'"); - - return true; - } catch (SQLException e) { - e.printStackTrace(); - Server.error(e); - return false; - } + return Server.storage.savePlayer(this); } public void setAppearance(byte hairColour, byte topColour, @@ -461,14 +272,17 @@ public class PlayerSave { this.male = male; this.skulled = skulled; } - public void setCombatStyle(byte combatStyle) { this.combatStyle = combatStyle; } - public void setExp(int stat, long exp) { + public void setExp(int stat, int exp) { this.exp[stat] = exp; } + + public void setExp(int[] is) { + this.exp = is; + } public void setFatigue(int fatigue) { this.fatigue = fatigue; @@ -522,6 +336,10 @@ public class PlayerSave { public void setLvl(int stat, int lvl) { this.lvl[stat] = lvl; } + + public void setCurStats(int[] stats) { + this.lvl = stats; + } public void setOwner(int owner) { this.owner = owner; @@ -577,7 +395,7 @@ public class PlayerSave { this.combatWindow = combatWindow; } - public void setStat(int stat, long exp, int lvl) { + public void setStat(int stat, int exp, int lvl) { this.exp[stat] = exp; this.lvl[stat] = lvl; } @@ -602,4 +420,16 @@ public class PlayerSave { public long getMuted() { return muted; } + + public List getInvItems() { + return invItems; + } + + public int getCombat() { + return combat; + } + + public int getSkillTotal() { + return skillTotal; + } } diff --git a/LoginServer/src/org/moparscape/msc/ls/model/World.java b/LoginServer/src/org/moparscape/msc/ls/model/World.java index 77a840b..db6f1c8 100644 --- a/LoginServer/src/org/moparscape/msc/ls/model/World.java +++ b/LoginServer/src/org/moparscape/msc/ls/model/World.java @@ -1,7 +1,7 @@ package org.moparscape.msc.ls.model; -import java.sql.ResultSet; import java.util.Collection; +import java.util.List; import java.util.TreeMap; import java.util.Map.Entry; @@ -10,113 +10,102 @@ import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.packetbuilder.loginserver.MiscPacketBuilder; import org.moparscape.msc.ls.util.DataConversions; - public class World { - private MiscPacketBuilder actionSender = new MiscPacketBuilder(); - private int id = -1; - private TreeMap players = new TreeMap(); - private TreeMap saves = new TreeMap(); - private IoSession session; + private MiscPacketBuilder actionSender = new MiscPacketBuilder(); + private int id = -1; + private TreeMap players = new TreeMap(); + private TreeMap saves = new TreeMap(); + private IoSession session; - public World(int id, IoSession session) { - this.id = id; - setSession(session); - } - - public void assosiateSave(PlayerSave save) { - saves.put(save.getUser(), save); - } - - public void clearPlayers() { - for (Entry player : getPlayers()) { - long user = player.getKey(); - for (World w : Server.getServer().getWorlds()) { - w.getActionSender().friendLogout(user); - } - System.out.println("Removed " + DataConversions.hashToUsername(user) + " from world " + id); + public World(int id, IoSession session) { + this.id = id; + setSession(session); } - players.clear(); - } - public MiscPacketBuilder getActionSender() { - return actionSender; - } + public void assosiateSave(PlayerSave save) { + saves.put(save.getUser(), save); + } - public Collection> getAssosiatedSaves() { - return saves.entrySet(); - } - - public int getID() { - return id; - } - - public Collection> getPlayers() { - return players.entrySet(); - } - - public PlayerSave getSave(long user) { - return saves.get(user); - } - - public IoSession getSession() { - return session; - } - - public boolean hasPlayer(long user) { - return players.containsKey(user); - } - - public void registerPlayer(long user, String ip) { - Server server = Server.getServer(); - ResultSet result; - try { - result = Server.db.getQuery("SELECT owner, block_private FROM `pk_players` WHERE `user`='" + user + "'"); - if (!result.next()) { - return; - } - int owner = result.getInt("owner"); - boolean blockPrivate = result.getInt("block_private") == 1; - - result = Server.db.getQuery("SELECT user FROM `pk_friends` WHERE `friend`='" + user + "'" + (blockPrivate ? " AND user IN (SELECT friend FROM `pk_friends` WHERE `user`='" + user + "')" : "")); - while (result.next()) { - long friend = result.getLong("user"); - World w = server.findWorld(friend); - if (w != null) { - w.getActionSender().friendLogin(friend, user, id); + public void clearPlayers() { + for (Entry player : getPlayers()) { + long user = player.getKey(); + for (World w : Server.getServer().getWorlds()) { + w.getActionSender().friendLogout(user); + } + System.out.println("Removed " + + DataConversions.hashToUsername(user) + " from world " + + id); } - } - long now = (int) (System.currentTimeMillis() / 1000); - Server.db.updateQuery("INSERT INTO `pk_logins`(`user`, `time`, `ip`) VALUES('" + user + "', '" + now + "', '" + ip + "')"); - Server.db.updateQuery("UPDATE `pk_players` SET login_date=" + now + ", login_ip='" + ip + "' WHERE user='" + user + "'"); - - players.put(user, owner); - System.out.println("Added " + DataConversions.hashToUsername(user) + " to world " + id); - } catch (Exception e) { - Server.error(e); - } - } - - public void setSession(IoSession session) { - this.session = session; - } - - public void unassosiateSave(PlayerSave save) { - saves.remove(save.getUser()); - } - - public void unregisterPlayer(long user) { - for (World w : Server.getServer().getWorlds()) { - w.getActionSender().friendLogout(user); - } - players.remove(user); - System.out.println("Removed " + DataConversions.hashToUsername(user) + " from world " + id); - - try { - Server.db.updateQuery("UPDATE `pk_players` SET online=0 WHERE user='" + user + "'"); - } catch (Exception e) { - Server.error(e); + players.clear(); } - } + public MiscPacketBuilder getActionSender() { + return actionSender; + } + + public Collection> getAssosiatedSaves() { + return saves.entrySet(); + } + + public int getID() { + return id; + } + + public Collection> getPlayers() { + return players.entrySet(); + } + + public PlayerSave getSave(long user) { + return saves.get(user); + } + + public IoSession getSession() { + return session; + } + + public boolean hasPlayer(long user) { + return players.containsKey(user); + } + + public void registerPlayer(long user, String ip) { + Server server = Server.getServer(); + try { + long owner = Server.storage.getOwner(user); + + List friends = Server.storage.getFriendsOnline(user); + if (friends != null) + for (long friend : friends) { + World w = server.findWorld(friend); + if (w != null) { + w.getActionSender().friendLogin(friend, user, id); + } + } + Server.storage.logLogin(user, ip); + Server.storage.logIn(ip, user); + players.put(user, owner); + System.out.println("Added " + DataConversions.hashToUsername(user) + + " to world " + id); + } catch (Exception e) { + Server.error(e); + } + } + + public void setSession(IoSession session) { + this.session = session; + } + + public void unassosiateSave(PlayerSave save) { + saves.remove(save.getUser()); + } + + public void unregisterPlayer(long user) { + for (World w : Server.getServer().getWorlds()) { + w.getActionSender().friendLogout(user); + } + players.remove(user); + System.out.println("Removed " + DataConversions.hashToUsername(user) + + " from world " + id); + Server.storage.setOnlineFlag(id, user); + } } diff --git a/LoginServer/src/org/moparscape/msc/ls/net/DatabaseConnection.java b/LoginServer/src/org/moparscape/msc/ls/net/DatabaseConnection.java index 5c9ea13..f78e3be 100644 --- a/LoginServer/src/org/moparscape/msc/ls/net/DatabaseConnection.java +++ b/LoginServer/src/org/moparscape/msc/ls/net/DatabaseConnection.java @@ -120,4 +120,8 @@ public class DatabaseConnection { throw new SQLException(e.getMessage() + ": '" + lastQuery + "'", e.getSQLState(), e.getErrorCode()); } } + + public java.sql.PreparedStatement prepareStatement(String statement) throws SQLException { + return con.prepareStatement(statement); + } } diff --git a/LoginServer/src/org/moparscape/msc/ls/packetbuilder/loginserver/PlayerLoginPacketBuilder.java b/LoginServer/src/org/moparscape/msc/ls/packetbuilder/loginserver/PlayerLoginPacketBuilder.java index c7af3ee..6ad89f5 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packetbuilder/loginserver/PlayerLoginPacketBuilder.java +++ b/LoginServer/src/org/moparscape/msc/ls/packetbuilder/loginserver/PlayerLoginPacketBuilder.java @@ -1,8 +1,6 @@ package org.moparscape.msc.ls.packetbuilder.loginserver; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; +import java.util.List; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.model.BankItem; @@ -89,19 +87,7 @@ public class PlayerLoginPacketBuilder { packet.addInt(item.getAmount()); } - ArrayList friendsWithUs = new ArrayList(); - try { - ResultSet result = Server.db.getQuery("SELECT p.user FROM `pk_friends` AS f INNER JOIN `pk_players` AS p ON p.user=f.friend WHERE p.block_private=0 AND f.user='" + save.getUser() + "'"); - while (result.next()) { - friendsWithUs.add(result.getLong("user")); - } - result = Server.db.getQuery("SELECT user FROM `pk_friends` WHERE friend='" + save.getUser() + "'"); - while (result.next()) { - friendsWithUs.add(result.getLong("user")); - } - } catch (SQLException e) { - Server.error(e); - } + List friendsWithUs = Server.storage.getFriendsOnline(save.getUser()); int friendCount = save.getFriendCount(); packet.addShort(friendCount); diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/BanHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/BanHandler.java index 3d9bcde..7e68d49 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/BanHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/BanHandler.java @@ -1,7 +1,5 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.ResultSet; - import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.model.World; @@ -11,43 +9,42 @@ import org.moparscape.msc.ls.packetbuilder.loginserver.ReplyPacketBuilder; import org.moparscape.msc.ls.packethandler.PacketHandler; import org.moparscape.msc.ls.util.DataConversions; - public class BanHandler implements PacketHandler { - private ReplyPacketBuilder builder = new ReplyPacketBuilder(); + private ReplyPacketBuilder builder = new ReplyPacketBuilder(); - public void handlePacket(Packet p, IoSession session) throws Exception { - final long uID = ((LSPacket) p).getUID(); - boolean banned = ((LSPacket) p).getID() == 4; - long user = p.readLong(); - long modhash = p.readLong(); + public void handlePacket(Packet p, IoSession session) throws Exception { + final long uID = ((LSPacket) p).getUID(); + boolean setBanned = ((LSPacket) p).getID() == 4; + long user = p.readLong(); + long modhash = p.readLong(); + + if (!Server.storage.playerExists(user)) { + builder.setSuccess(false); + builder.setReply("There is not an account by that username"); + } else if (setBanned && Server.storage.getGroupID(user) < 3) { + builder.setSuccess(false); + builder.setReply("You cannot ban a (p)mod or admin!"); + } else if (Server.storage.ban(setBanned, user)) { + builder.setSuccess(false); + builder.setReply("There is not an account by that username"); + } else { + World w = Server.getServer().findWorld(user); + if (w != null) { + w.getActionSender().logoutUser(user); + } + if (setBanned) + Server.storage.logBan(user, modhash); + builder.setSuccess(true); + builder.setReply(DataConversions.hashToUsername(user) + + " has been " + (setBanned ? "banned" : "unbanned")); + } + builder.setUID(uID); + + LSPacket temp = builder.getPacket(); + if (temp != null) { + session.write(temp); + } - ResultSet result = Server.db.getQuery("SELECT u.group_id, p.playermod, p.owner FROM `users` AS u INNER JOIN `pk_players` AS p ON p.owner=u.id WHERE p.user='" + user + "'"); - if (!result.next()) { - builder.setSuccess(false); - builder.setReply("There is not an account by that username"); - } else if (banned && (result.getInt("group_id") < 3 || result.getInt("playermod") == 1)) { - builder.setSuccess(false); - builder.setReply("You cannot ban a (p)mod or admin!"); - } else if (Server.db.updateQuery("UPDATE `pk_players` SET `banned`='" + (banned ? "1" : "0") + "' WHERE `user` LIKE '" + user + "'") == 0) { - builder.setSuccess(false); - builder.setReply("There is not an account by that username"); - } else { - World w = Server.getServer().findWorld(user); - if (w != null) { - w.getActionSender().logoutUser(user); - } - if (banned) - Server.db.updateQuery("INSERT `pk_banlog` VALUES('" + user + "','" + modhash + "','" + (System.currentTimeMillis() / 1000) + "')"); - builder.setSuccess(true); - builder.setReply(DataConversions.hashToUsername(user) + " has been " + (banned ? "banned" : "unbanned")); } - builder.setUID(uID); - - LSPacket temp = builder.getPacket(); - if (temp != null) { - session.write(temp); - } - - } } diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/FriendHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/FriendHandler.java index 5a5a208..ddb695a 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/FriendHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/FriendHandler.java @@ -1,7 +1,5 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.SQLException; - import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.model.PlayerSave; @@ -10,78 +8,63 @@ import org.moparscape.msc.ls.net.LSPacket; import org.moparscape.msc.ls.net.Packet; import org.moparscape.msc.ls.packethandler.PacketHandler; - public class FriendHandler implements PacketHandler { - public void handlePacket(Packet p, IoSession session) throws Exception { - World world = (World) session.getAttachment(); - Server server = Server.getServer(); + public void handlePacket(Packet p, IoSession session) throws Exception { + World world = (World) session.getAttachment(); + Server server = Server.getServer(); - long user = p.readLong(); - long friend = p.readLong(); + long user = p.readLong(); + long friend = p.readLong(); - World w; - PlayerSave save = server.findSave(user, world); - switch (((LSPacket) p).getID()) { - case 10: // Send PM - boolean avoidBlock = p.readByte() == 1; - byte[] message = p.getRemainingData(); - w = server.findWorld(friend); - if (w != null) { - w.getActionSender().sendPM(user, friend, avoidBlock, message); - } - break; - case 11: // Add friend - try { - save.addFriend(friend); - Server.db.updateQuery("INSERT INTO `pk_friends`(`user`, `friend`) VALUES('" + user + "', '" + friend + "')"); - if (Server.db.getQuery("SELECT 1 FROM `pk_players` AS p LEFT JOIN `pk_friends` AS f ON f.user=p.user WHERE (p.block_private=0 OR f.friend='" + user + "') AND p.user='" + friend + "'").next()) { - w = server.findWorld(friend); - if (w != null) { - world.getActionSender().friendLogin(user, friend, w.getID()); - } + World w; + PlayerSave save = server.findSave(user, world); + switch (((LSPacket) p).getID()) { + case 10: // Send PM + boolean avoidBlock = p.readByte() == 1; + byte[] message = p.getRemainingData(); + w = server.findWorld(friend); + if (w != null) { + w.getActionSender().sendPM(user, friend, avoidBlock, message); + } + break; + case 11: // Add friend + save.addFriend(friend); + Server.storage.addFriend(user, friend); + if (Server.storage.addFriend_isOnline0(user, friend)) { + w = server.findWorld(friend); + if (w != null) { + world.getActionSender() + .friendLogin(user, friend, w.getID()); + } + } + if (Server.storage.addFriend_isOnline1(friend, user)) { + w = server.findWorld(friend); + if (w != null) { + w.getActionSender() + .friendLogin(friend, user, world.getID()); + } + } + break; + case 12: // Remove friend + save.removeFriend(friend); + Server.storage.removeFriend(user, friend); + if (Server.storage.removeFriend_isOnline(user)) { + w = server.findWorld(friend); + if (w != null) { + w.getActionSender().friendLogout(friend, user); + } + } + break; + case 13: // Add ignore + save.addIgnore(friend); + Server.storage.addIgnore(user, friend); + break; + case 14: // Remove ignore + save.removeIgnore(friend); + Server.storage.removeIgnore(user, friend); + break; } - if (Server.db.getQuery("SELECT 1 FROM `pk_players` AS p LEFT JOIN `pk_friends` AS f ON f.friend=p.user WHERE p.block_private=1 AND f.user='" + friend + "' AND p.user='" + user + "'").next()) { - w = server.findWorld(friend); - if (w != null) { - w.getActionSender().friendLogin(friend, user, world.getID()); - } - } - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 12: // Remove friend - try { - save.removeFriend(friend); - Server.db.updateQuery("DELETE FROM `pk_friends` WHERE `user` LIKE '" + user + "' AND `friend` LIKE '" + friend + "'"); - if (Server.db.getQuery("SELECT 1 FROM `pk_players` WHERE block_private=1 AND user='" + user + "'").next()) { - w = server.findWorld(friend); - if (w != null) { - w.getActionSender().friendLogout(friend, user); - } - } - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 13: // Add ignore - try { - save.addIgnore(friend); - Server.db.updateQuery("INSERT INTO `pk_ignores`(`user`, `ignore`) VALUES('" + user + "', '" + friend + "')"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 14: // Remove ignore - try { - save.removeIgnore(friend); - Server.db.updateQuery("DELETE FROM `pk_ignores` WHERE `user` LIKE '" + user + "' AND `ignore` LIKE '" + friend + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; } - } } diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/GameSettingHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/GameSettingHandler.java index e468f72..fd50e53 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/GameSettingHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/GameSettingHandler.java @@ -1,7 +1,5 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.SQLException; - import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.model.World; @@ -16,50 +14,7 @@ public class GameSettingHandler implements PacketHandler { long user = p.readLong(); boolean on = p.readByte() == 1; int idx = (int) p.readByte(); - switch (idx) { - case 0: // Camera Auto - try { - Server.db.updateQuery("UPDATE `pk_players` SET cameraauto=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 2: // One Mouse - try { - Server.db.updateQuery("UPDATE `pk_players` SET onemouse=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 3: // Sound Off - try { - Server.db.updateQuery("UPDATE `pk_players` SET soundoff=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 4: // Show Roof - try { - Server.db.updateQuery("UPDATE `pk_players` SET showroof=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 5: // Auto Screenshot - try { - Server.db.updateQuery("UPDATE `pk_players` SET autoscreenshot=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 6: // Combat Window - try { - Server.db.updateQuery("UPDATE `pk_players` SET combatwindow=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - } + Server.storage.setGameSettings(idx, on, user); Server.getServer().findSave(user, world).setGameSetting(idx, on); } diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/KillHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/KillHandler.java index 757a4e4..3701bd8 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/KillHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/KillHandler.java @@ -1,21 +1,17 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.SQLException; - import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.net.Packet; import org.moparscape.msc.ls.packethandler.PacketHandler; - public class KillHandler implements PacketHandler { - public void handlePacket(Packet p, IoSession session) throws Exception { - try { - Server.db.updateQuery("INSERT INTO `pk_kills`(`user`, `killed`, `time`, `type`) VALUES('" + p.readLong() + "', '" + p.readLong() + "', " + (int) (System.currentTimeMillis() / 1000) + ", " + p.readByte() + ")"); - } catch (SQLException e) { - e.printStackTrace(); + public void handlePacket(Packet p, IoSession session) throws Exception { + long user = p.readLong(); + long killed = p.readLong(); + byte type = p.readByte(); + Server.storage.logKill(user, killed, type); } - } } diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerLoginHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerLoginHandler.java index ed60c6c..b610cda 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerLoginHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerLoginHandler.java @@ -1,7 +1,5 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Map.Entry; @@ -15,95 +13,89 @@ import org.moparscape.msc.ls.packetbuilder.loginserver.PlayerLoginPacketBuilder; import org.moparscape.msc.ls.packethandler.PacketHandler; import org.moparscape.msc.ls.util.DataConversions; - public class PlayerLoginHandler implements PacketHandler { - public static ArrayList badClients = new ArrayList(); - private PlayerLoginPacketBuilder builder = new PlayerLoginPacketBuilder(); + public static ArrayList badClients = new ArrayList(); + private PlayerLoginPacketBuilder builder = new PlayerLoginPacketBuilder(); - public void handlePacket(Packet p, IoSession session) throws Exception { - final long uID = ((LSPacket) p).getUID(); - World world = (World) session.getAttachment(); - long user = p.readLong(); - String ip = DataConversions.IPToString(p.readLong()); - String pass = p.readString(32).trim(); - String className = p.readString(); - byte loginCode = validatePlayer(user, pass, ip); + public void handlePacket(Packet p, IoSession session) throws Exception { + final long uID = ((LSPacket) p).getUID(); + World world = (World) session.getAttachment(); + long user = p.readLong(); + String ip = DataConversions.IPToString(p.readLong()); + String pass = p.readString(32).trim(); + String className = p.readString(); + byte loginCode = validatePlayer(user, pass, ip); - builder.setUID(uID); - if (loginCode == 0 || loginCode == 1 || loginCode == 99) { - try { - badClients.add(DataConversions.hashToUsername(user)); - System.out.println("Class: " + className + " Player: " + DataConversions.hashToUsername(user)); - } catch (Exception e) { - System.out.println("Exception in classname printer :" + e.getMessage()); - } - // if(!className.equals("ORG.RSCDAEMON.CLIENT.MUDCLIENT")) { - // System.out.println(DataConversions.hashToUsername(user) + - // " was caught by a trap"); - // try { - // Server.db.updateQuery("INSERT INTO `pk_traps`(`user`, `time`, `ip`, `details`) VALUES('" - // + user + "', '" + (int)(System.currentTimeMillis() / 1000) + - // "', '" + ip + "', 'Unknown main class: \"" + className +"\"')"); - // } catch(Exception e) { } - // } - try { - Server.db.updateQuery("UPDATE `pk_players` SET online=1 WHERE user='" + user + "'"); - } catch (Exception e) { - } + builder.setUID(uID); + if (loginCode == 0 || loginCode == 1 || loginCode == 99) { + try { + badClients.add(DataConversions.hashToUsername(user)); + System.out.println("Class: " + className + " Player: " + + DataConversions.hashToUsername(user)); + } catch (Exception e) { + System.out.println("Exception in classname printer :" + + e.getMessage()); + } + // if(!className.equals("ORG.RSCDAEMON.CLIENT.MUDCLIENT")) { + // System.out.println(DataConversions.hashToUsername(user) + + // " was caught by a trap"); + // try { + // Server.db.updateQuery("INSERT INTO `pk_traps`(`user`, `time`, `ip`, `details`) VALUES('" + // + user + "', '" + (int)(System.currentTimeMillis() / 1000) + + // "', '" + ip + "', 'Unknown main class: \"" + className +"\"')"); + // } catch(Exception e) { } + // } + Server.storage.setOnlineFlag(world.getID(), user); - builder.setPlayer(Server.getServer().findSave(user, world), loginCode); - world.registerPlayer(user, ip); - } else { - builder.setPlayer(null, loginCode); + builder.setPlayer(Server.getServer().findSave(user, world), + loginCode); + world.registerPlayer(user, ip); + } else { + builder.setPlayer(null, loginCode); + } + + LSPacket packet = builder.getPacket(); + if (packet != null) { + session.write(packet); + } } - LSPacket packet = builder.getPacket(); - if (packet != null) { - session.write(packet); - } - } + private byte validatePlayer(long user, String pass, String ip) { + Server server = Server.getServer(); + byte returnVal = 0; - private byte validatePlayer(long user, String pass, String ip) { - Server server = Server.getServer(); - byte returnVal = 0; + if (!Server.storage.playerExists(user)) + return 2; + if (!Auth.check_auth(DataConversions.hashToUsername(user), pass, + new StringBuilder())) { + return 2; + } - try { - ResultSet result = Server.db.getQuery("SELECT banned, owner, group_id FROM `pk_players` WHERE `user` = '" + user + "'"); - if (!result.next()) { - return 2; - } - if (!Auth.check_auth(DataConversions.hashToUsername(user), pass, new StringBuilder())) { - return 2; - } - - if (result.getInt("banned") == 1) { - System.out.println("Banned player: " + DataConversions.hashToUsername(user) + " trying to login."); + if (Server.storage.isBanned(user)) { + System.out.println("Banned player: " + + DataConversions.hashToUsername(user) + + " trying to login."); return 6; - } - - if (result.getInt("group_id") >= 5) { - returnVal = 99; - } - - int owner = result.getInt("owner"); - for (World w : server.getWorlds()) { - for (Entry player : w.getPlayers()) { - if (player.getKey() == user) { - return 3; - } - if (player.getValue() == owner) { - return 9; - } } - if (w.hasPlayer(user)) { - return 3; + + if (Server.storage.getGroupID(user) >= 5) { + returnVal = 99; } - } - return returnVal; - } catch (SQLException e) { - System.out.println("Exception in PlayerLoginHandler :" + e.getMessage()); - //System.out.println(e.getMessage(), e); - return 7; + + long owner = Server.storage.getOwner(user); + for (World w : server.getWorlds()) { + for (Entry player : w.getPlayers()) { + if (player.getKey() == user) { + return 3; + } + if (player.getValue() == owner) { + return 9; + } + } + if (w.hasPlayer(user)) { + return 3; + } + } + return returnVal; } - } } \ No newline at end of file diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerSaveHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerSaveHandler.java index a969769..7cdb870 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerSaveHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PlayerSaveHandler.java @@ -36,7 +36,7 @@ public class PlayerSaveHandler implements PacketHandler { //save.setPoints(p.readInt()); for (int i = 0; i < 18; i++) { - save.setStat(i, p.readLong(), p.readShort()); + save.setStat(i, p.readInt(), p.readShort()); } int invCount = p.readShort(); diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PrivacySettingHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PrivacySettingHandler.java index 559694e..689dab0 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PrivacySettingHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/PrivacySettingHandler.java @@ -1,7 +1,6 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.util.List; import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; @@ -9,59 +8,44 @@ import org.moparscape.msc.ls.model.World; import org.moparscape.msc.ls.net.Packet; import org.moparscape.msc.ls.packethandler.PacketHandler; - public class PrivacySettingHandler implements PacketHandler { - public void handlePacket(Packet p, IoSession session) throws Exception { - World world = (World) session.getAttachment(); - Server server = Server.getServer(); + public void handlePacket(Packet p, IoSession session) throws Exception { + World world = (World) session.getAttachment(); + Server server = Server.getServer(); - long user = p.readLong(); - boolean on = p.readByte() == 1; - int idx = (int) p.readByte(); - switch (idx) { - case 0: // Chat block - try { - Server.db.updateQuery("UPDATE `pk_players` SET block_chat=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 1: // Private block - try { - Server.db.updateQuery("UPDATE `pk_players` SET block_private=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - ResultSet result = Server.db.getQuery("SELECT user FROM `pk_friends` WHERE friend='" + user + "' AND user NOT IN (SELECT friend FROM `pk_friends` WHERE user='" + user + "')"); - while (result.next()) { - long friend = result.getLong("user"); - World w = server.findWorld(friend); - if (w != null) { - if (on) { - w.getActionSender().friendLogout(friend, user); - } else { - w.getActionSender().friendLogin(friend, user, world.getID()); + long user = p.readLong(); + boolean on = p.readByte() == 1; + int idx = (int) p.readByte(); + int isOn = (on ? 1 : 0); + switch (idx) { + case 0: // Chat block + Server.storage.chatBlock(isOn, user); + break; + case 1: // Private block + Server.storage.privateBlock(isOn, user); + List friends = Server.storage + .getPrivateBlockFriendsOnline(user); + for (long friend : friends) { + World w = server.findWorld(friend); + if (w != null) { + if (on) { + w.getActionSender().friendLogout(friend, user); + } else { + w.getActionSender().friendLogin(friend, user, + world.getID()); + } + } } - } + break; + case 2: // Trade block + Server.storage.tradeBlock(isOn, user); + break; + case 3: // Duel block + Server.storage.duelBlock(isOn, user); + break; } - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 2: // Trade block - try { - Server.db.updateQuery("UPDATE `pk_players` SET block_trade=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; - case 3: // Duel block - try { - Server.db.updateQuery("UPDATE `pk_players` SET block_duel=" + (on ? 1 : 0) + " WHERE user='" + user + "'"); - } catch (SQLException e) { - Server.error(e.getMessage()); - } - break; + server.findSave(user, world).setPrivacySetting(idx, on); } - server.findSave(user, world).setPrivacySetting(idx, on); - } } diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/RegisterWorld.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/RegisterWorld.java index 5aec3c8..aebdce3 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/RegisterWorld.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/RegisterWorld.java @@ -1,7 +1,5 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.SQLException; - import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.model.World; @@ -11,62 +9,53 @@ import org.moparscape.msc.ls.packetbuilder.loginserver.WorldRegisteredPacketBuil import org.moparscape.msc.ls.packethandler.PacketHandler; import org.moparscape.msc.ls.util.DataConversions; - public class RegisterWorld implements PacketHandler { - private WorldRegisteredPacketBuilder builder = new WorldRegisteredPacketBuilder(); + private WorldRegisteredPacketBuilder builder = new WorldRegisteredPacketBuilder(); - public void handlePacket(Packet p, IoSession session) throws Exception { - final long uID = ((LSPacket) p).getUID(); - builder.setUID(uID); - builder.setSuccess(false); + public void handlePacket(Packet p, IoSession session) throws Exception { + final long uID = ((LSPacket) p).getUID(); + builder.setUID(uID); + builder.setSuccess(false); - Server server = Server.getServer(); - if (((LSPacket) p).getID() == 1) { - int id = p.readShort(); - if (server.getWorld(id) == null) { - World world = server.getIdleWorld(id); - if (world == null) { - world = new World(id, session); - server.registerWorld(world); - System.out.println("Registering world: " + id); - try { - if (id == 1) - Server.db.updateQuery("UPDATE `pk_players` SET online=0"); - } catch (SQLException e) { - Server.error(e); - } + Server server = Server.getServer(); + if (((LSPacket) p).getID() == 1) { + int id = p.readShort(); + if (server.getWorld(id) == null) { + World world = server.getIdleWorld(id); + if (world == null) { + world = new World(id, session); + server.registerWorld(world); + System.out.println("Registering world: " + id); + Server.storage.resetOnlineFlag(id); + } else { + world.setSession(session); + server.setIdle(world, false); + System.out.println("Reattached to world " + id); + Server.storage.resetOnlineFlag(id); + + } + int playerCount = p.readShort(); + for (int i = 0; i < playerCount; i++) { + world.registerPlayer(p.readLong(), + DataConversions.IPToString(p.readLong())); + } + session.setAttachment(world); + builder.setSuccess(true); + } } else { - world.setSession(session); - server.setIdle(world, false); - System.out.println("Reattached to world " + id); - try { - Server.db.updateQuery("UPDATE `pk_players` SET online=0"); - } catch (SQLException e) { - Server.error(e); - } + World world = (World) session.getAttachment(); + server.unregisterWorld(world); + System.out.println("UnRegistering world: " + world.getID()); + session.setAttachment(null); + builder.setSuccess(true); } - int playerCount = p.readShort(); - for (int i = 0; i < playerCount; i++) { - world.registerPlayer(p.readLong(), DataConversions.IPToString(p.readLong())); + + LSPacket temp = builder.getPacket(); + if (temp != null) { + session.write(temp); } - session.setAttachment(world); - builder.setSuccess(true); - } - } else { - World world = (World) session.getAttachment(); - - server.unregisterWorld(world); - System.out.println("UnRegistering world: " + world.getID()); - session.setAttachment(null); - builder.setSuccess(true); } - LSPacket temp = builder.getPacket(); - if (temp != null) { - session.write(temp); - } - } - } diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/ReportHandler.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/ReportHandler.java index e6b9062..ed08a5e 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/ReportHandler.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/ReportHandler.java @@ -1,34 +1,30 @@ package org.moparscape.msc.ls.packethandler.loginserver; -import java.sql.SQLException; - import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.model.World; import org.moparscape.msc.ls.net.Packet; import org.moparscape.msc.ls.packethandler.PacketHandler; - public class ReportHandler implements PacketHandler { - public void handlePacket(Packet p, IoSession session) throws Exception { - World world = (World) session.getAttachment(); + public void handlePacket(Packet p, IoSession session) throws Exception { + World world = (World) session.getAttachment(); - final long user = p.readLong(); - final long reported = p.readLong(); - final byte reason = p.readByte(); - world.getActionSender().requestReportInfo(reported, new PacketHandler() { - public void handlePacket(Packet p, IoSession session) throws Exception { - int x = p.readShort(); - int y = p.readShort(); - String status = p.readString(); - try { - Server.db.updateQuery("INSERT INTO `pk_reports`(`from`, `about`, `time`, `reason`, `x`, `y`, `status`) VALUES('" + user + "', '" + reported + "', '" + (System.currentTimeMillis() / 1000) + "', '" + reason + "', '" + x + "', '" + y + "', '" + status + "')"); - } catch (SQLException e) { - Server.error(e); - } - } - }); - } + final long user = p.readLong(); + final long reported = p.readLong(); + final byte reason = p.readByte(); + world.getActionSender().requestReportInfo(reported, + new PacketHandler() { + public void handlePacket(Packet p, IoSession session) + throws Exception { + int x = p.readShort(); + int y = p.readShort(); + String status = p.readString(); + Server.storage.logReport(user, reported, reason, x, y, + status); + } + }); + } } diff --git a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/Tradelog.java b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/Tradelog.java index 5cfe1c7..0dd07eb 100644 --- a/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/Tradelog.java +++ b/LoginServer/src/org/moparscape/msc/ls/packethandler/loginserver/Tradelog.java @@ -5,17 +5,16 @@ import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.net.Packet; import org.moparscape.msc.ls.packethandler.PacketHandler; - public class Tradelog implements PacketHandler { - public void handlePacket(Packet p, IoSession session) throws Exception { - long from = p.readLong(); - long to = p.readLong(); - int item = p.readInt(); - long amount = p.readLong(); - int x = p.readInt(); - int y = p.readInt(); - int type = p.readInt(); - long date = (System.currentTimeMillis() / 1000); - Server.db.updateQuery("INSERT `pk_tradelog` VALUES('" + from + "','" + to + "','" + date + "','" + item + "','" + x + "','" + y + "','" + amount + "','" + type + "')"); - } + public void handlePacket(Packet p, IoSession session) throws Exception { + long from = p.readLong(); + long to = p.readLong(); + int item = p.readInt(); + long amount = p.readLong(); + int x = p.readInt(); + int y = p.readInt(); + int type = p.readInt(); + long date = (System.currentTimeMillis() / 1000); + Server.storage.logTrade(from, to, item, amount, x, y, type, date); + } } diff --git a/LoginServer/src/org/moparscape/msc/ls/persistence/StorageMedium.java b/LoginServer/src/org/moparscape/msc/ls/persistence/StorageMedium.java new file mode 100644 index 0000000..48b295c --- /dev/null +++ b/LoginServer/src/org/moparscape/msc/ls/persistence/StorageMedium.java @@ -0,0 +1,40 @@ +package org.moparscape.msc.ls.persistence; + +import java.util.List; + +import org.moparscape.msc.ls.model.PlayerSave; + +public interface StorageMedium { + public boolean savePlayer(PlayerSave s); + public void shutdown(); + public void logTrade(long from, long to, int item, long amount, int x, + int y, int type, long date); + public void logReport(long user, long reported, byte reason, int x, + int y, String status); + public void resetOnlineFlag(int world); + public void logKill(long user, long killed, byte type); + public void addFriend(long user, long friend); + public boolean addFriend_isOnline0(long user, long friend); + public boolean addFriend_isOnline1(long friend, long user); + public void removeFriend(long user, long friend); + public boolean removeFriend_isOnline(long user); + public void addIgnore(long user, long friend); + public void removeIgnore(long user, long friend); + public List getFriendsOnline(long user); + public void chatBlock(int on, long user); + public void privateBlock(int on, long user); + public List getPrivateBlockFriendsOnline(long user); + public void tradeBlock(int on, long user); + public void duelBlock(int on, long user); + public boolean playerExists(long user); + public boolean isBanned(long user); + public int getGroupID(long user); + public long getOwner(long user); + public void setOnlineFlag(int id, long user); + public boolean ban(boolean setBanned, long user); + public void logBan(long user, long modhash); + public void setGameSettings(int idx, boolean on, long user); + public PlayerSave loadPlayer(long user); + public void logLogin(long user, String ip); + public void logIn(String ip, long user); +} diff --git a/LoginServer/src/org/moparscape/msc/ls/persistence/StorageMediumFactory.java b/LoginServer/src/org/moparscape/msc/ls/persistence/StorageMediumFactory.java new file mode 100644 index 0000000..51607ba --- /dev/null +++ b/LoginServer/src/org/moparscape/msc/ls/persistence/StorageMediumFactory.java @@ -0,0 +1,10 @@ +package org.moparscape.msc.ls.persistence; + +public class StorageMediumFactory { + + public static StorageMedium createMedium(String className) throws Exception { + return Class.forName(className).asSubclass(StorageMedium.class) + .newInstance(); + } + +} diff --git a/LoginServer/src/org/moparscape/msc/ls/persistence/impl/MySQL.java b/LoginServer/src/org/moparscape/msc/ls/persistence/impl/MySQL.java new file mode 100644 index 0000000..3344c5d --- /dev/null +++ b/LoginServer/src/org/moparscape/msc/ls/persistence/impl/MySQL.java @@ -0,0 +1,718 @@ +package org.moparscape.msc.ls.persistence.impl; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.moparscape.msc.ls.model.BankItem; +import org.moparscape.msc.ls.model.InvItem; +import org.moparscape.msc.ls.model.PlayerSave; +import org.moparscape.msc.ls.net.DatabaseConnection; +import org.moparscape.msc.ls.persistence.StorageMedium; +import org.moparscape.msc.ls.util.Config; +import org.moparscape.msc.ls.util.DataConversions; + +public class MySQL implements StorageMedium { + + private final DatabaseConnection conn; + + public MySQL() { + conn = new DatabaseConnection(); + } + + @Override + public boolean savePlayer(PlayerSave s) { + if (!playerExists(s.getUser())) { + return false; + } + + PreparedStatement statement; + try { + updateLongs(Statements.save_DeleteBank, s.getUser()); + + if (s.getBankCount() > 0) { + statement = conn.prepareStatement(Statements.save_AddBank); + int slot = 0; + for (BankItem item : s.getBankItems()) { + statement.setLong(1, s.getUser()); + statement.setInt(2, item.getID()); + statement.setInt(3, item.getAmount()); + statement.setInt(4, slot); + statement.addBatch(); + } + statement.executeBatch(); + } + + updateLongs(Statements.save_DeleteInv, s.getUser()); + + if (s.getInvCount() > 0) { + statement = conn.prepareStatement(Statements.save_AddInvItem); + int slot = 0; + for (InvItem item : s.getInvItems()) { + statement.setLong(1, s.getUser()); + statement.setInt(2, item.getID()); + statement.setInt(3, item.getAmount()); + statement.setInt(4, (item.isWielded() ? 1 : 0)); + statement.setInt(5, slot++); + statement.addBatch(); + } + statement.executeBatch(); + } + + updateLongs(Statements.save_DeleteQuests, s.getUser()); + + statement = conn.prepareStatement(Statements.save_AddQuest); + Set keys = s.getQuestStages().keySet(); + for (int id : keys) { + statement.setLong(1, s.getUser()); + statement.setInt(2, id); + statement.setInt(3, s.getQuestStage(id)); + statement.addBatch(); + } + statement.executeBatch(); + + statement = conn.prepareStatement(Statements.save_UpdateBasicInfo); + statement.setInt(1, s.getCombat()); + statement.setInt(2, s.getSkillTotal()); + statement.setInt(3, s.getX()); + statement.setInt(4, s.getY()); + statement.setInt(5, s.getFatigue()); + statement.setInt(6, s.getHairColour()); + statement.setInt(7, s.getTopColour()); + statement.setInt(8, s.getTrouserColour()); + statement.setInt(9, s.getSkinColour()); + statement.setInt(10, s.getHeadSprite()); + statement.setInt(11, s.getBodySprite()); + statement.setInt(12, s.isMale() ? 1 : 0); + statement.setLong(13, s.getSkullTime()); + statement.setInt(14, s.getCombatStyle()); + statement.setInt(15, s.getQuestPoints()); + statement.setLong(16, s.getUser()); + statement.executeUpdate(); + + String query = "UPDATE `" + Statements.PREFIX + "experience` SET "; + for (int i = 0; i < 18; i++) + query += "`exp_" + Config.statArray[i] + "`=" + s.getExp(i) + + ","; + + conn.updateQuery(query.substring(0, query.length() - 1) + + " WHERE `user`=" + s.getUser()); + + query = "UPDATE `" + Statements.PREFIX + "curstats` SET "; + for (int i = 0; i < 18; i++) + query += "`cur_" + Config.statArray[i] + "`=" + s.getStat(i) + + ","; + + conn.updateQuery(query.substring(0, query.length() - 1) + + " WHERE `user`=" + s.getUser()); + + updateLongs(Statements.save_SetEventCD, s.getEventCD() / 1000, s.getUser()); + + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + @Override + public void shutdown() { + try { + conn.close(); + } catch (SQLException e) { + System.out.println("Unable to cleanly close MySQL connection"); + } + } + + @Override + public void logTrade(long from, long to, int item, long amount, int x, + int y, int type, long date) { + PreparedStatement logTrade = null; + try { + logTrade = conn.prepareStatement(Statements.logTrade); + + logTrade.setLong(1, from); + logTrade.setLong(2, to); + logTrade.setLong(3, date); + logTrade.setInt(4, item); + logTrade.setInt(5, x); + logTrade.setInt(6, y); + logTrade.setLong(7, amount); + logTrade.setInt(8, type); + + logTrade.executeUpdate(); + } catch (SQLException e) { + if (logTrade != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + Statements.logTrade); + + } + } + + @Override + public void logReport(long user, long reported, byte reason, int x, int y, + String status) { + PreparedStatement logReport = null; + try { + logReport = conn.prepareStatement(Statements.logReport); + + logReport.setLong(1, user); + logReport.setLong(2, reported); + logReport.setLong(3, System.currentTimeMillis() / 1000); + logReport.setByte(4, reason); + logReport.setInt(5, x); + logReport.setInt(6, y); + logReport.setString(7, status); + + logReport.executeUpdate(); + } catch (SQLException e) { + if (logReport != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + Statements.logReport); + + } + } + + @Override + public void logKill(long user, long killed, byte type) { + PreparedStatement logKill = null; + try { + logKill = conn.prepareStatement(Statements.logKill); + + logKill.setLong(1, user); + logKill.setLong(2, killed); + logKill.setLong(3, System.currentTimeMillis() / 1000); + logKill.setByte(4, type); + + logKill.executeUpdate(); + } catch (SQLException e) { + if (logKill != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + Statements.logKill); + + } + } + + @Override + public void resetOnlineFlag(int world) { + PreparedStatement resetOnlineFlag = null; + try { + resetOnlineFlag = conn.prepareStatement(Statements.resetOnlineFlag); + + resetOnlineFlag.setInt(1, world); + + resetOnlineFlag.executeUpdate(); + } catch (SQLException e) { + if (resetOnlineFlag != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + Statements.resetOnlineFlag); + + } + } + + @Override + public void addFriend(long user, long friend) { + updateLongs(Statements.addFriend, user, friend); + } + + @Override + public boolean addFriend_isOnline0(long user, long friend) { + return hasNextFromLongs(Statements.addFriend_isOnline0, user, friend); + } + + @Override + public boolean addFriend_isOnline1(long friend, long user) { + return hasNextFromLongs(Statements.addFriend_isOnline1, friend, user); + } + + @Override + public void removeFriend(long user, long friend) { + updateLongs(Statements.removeFriend, user, friend); + } + + @Override + public boolean removeFriend_isOnline(long user) { + return hasNextFromLongs(Statements.removeFriend_isOnline, user); + } + + @Override + public void addIgnore(long user, long friend) { + updateLongs(Statements.addIgnore, user, friend); + } + + @Override + public void removeIgnore(long user, long friend) { + updateLongs(Statements.removeIgnore, user, friend); + } + + @Override + public List getFriendsOnline(long user) { + try { + List list = longListFromResultSet( + resultSetFromLongs(Statements.friendsList0, user), "user"); + list.addAll(longListFromResultSet( + resultSetFromLongs(Statements.friendsList1,user), "user")); + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + @Override + public void chatBlock(int on, long user) { + updateIntsLongs(Statements.chatBlock, new int[] { on }, + new long[] { user }); + } + + @Override + public void privateBlock(int on, long user) { + updateIntsLongs(Statements.privateBlock, new int[] { on }, + new long[] { user }); + } + + @Override + public List getPrivateBlockFriendsOnline(long user) { + try { + return longListFromResultSet( + resultSetFromLongs(Statements.privateBlock_online, user, + user), "user"); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } + } + + @Override + public void tradeBlock(int on, long user) { + updateIntsLongs(Statements.tradeBlock, new int[] { on }, + new long[] { user }); + } + + @Override + public void duelBlock(int on, long user) { + updateIntsLongs(Statements.duelBlock, new int[] { on }, + new long[] { user }); + } + + @Override + public boolean playerExists(long user) { + return hasNextFromLongs(Statements.basicInfo, user); + } + + @Override + public boolean isBanned(long user) { + try { + ResultSet res = resultSetFromLongs(Statements.basicInfo, user); + res.next(); + return res.getInt("banned") == 1; + } catch (SQLException e) { + e.printStackTrace(); + return true; + } + } + + @Override + public int getGroupID(long user) { + try { + ResultSet res = resultSetFromLongs(Statements.basicInfo, user); + res.next(); + return res.getInt("group_id"); + } catch (SQLException e) { + e.printStackTrace(); + // Normal user = 1 + return 1; + } + } + + @Override + public long getOwner(long user) { + try { + ResultSet res = resultSetFromLongs(Statements.basicInfo, user); + res.next(); + return res.getLong("owner"); + } catch (SQLException e) { + e.printStackTrace(); + return 0L; + } + } + + @Override + public void setOnlineFlag(int id, long user) { + updateIntsLongs(Statements.setOnlineFlag, new int[] { id }, + new long[] { user }); + } + + @Override + public void logBan(long user, long modhash) { + updateLongs(Statements.logBan, user, modhash, + (System.currentTimeMillis() / 1000)); + } + + @Override + public boolean ban(boolean setBanned, long user) { + updateLongs(Statements.setBanned, (setBanned ? 1 : 0), user); + return isBanned(user); + } + + private static final String[] gameSettings = { "cameraauto", "", + "onemouse", "soundoff", "showroof", "autoscreenshot", + "combatwindow" }; + + @Override + public void setGameSettings(int idx, boolean on, long user) { + try { + conn.updateQuery("UPDATE `" + Statements.PREFIX + "players` SET " + + gameSettings[idx] + "=" + (on ? 1 : 0) + " WHERE user='" + + user + "'"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public PlayerSave loadPlayer(long user) { + PlayerSave save = new PlayerSave(user); + ResultSet result = resultSetFromLongs(Statements.playerData, user); + try { + if (!result.next()) { + return save; + } + + save.setEventCD(result.getLong("eventcd")); + save.setOwner(result.getInt("owner"), result.getInt("group_id"), + result.getLong("sub_expires")); + save.setMuted(result.getLong("muted")); + + save.setLogin(result.getLong("login_date"), + DataConversions.IPToLong(result.getString("login_ip"))); + save.setLocation(result.getInt("x"), result.getInt("y")); + + save.setFatigue(result.getInt("fatigue")); + save.setCombatStyle((byte) result.getInt("combatstyle")); + + save.setPrivacy(result.getInt("block_chat") == 1, + result.getInt("block_private") == 1, + result.getInt("block_trade") == 1, + result.getInt("block_duel") == 1); + save.setSettings(result.getInt("cameraauto") == 1, + result.getInt("onemouse") == 1, + result.getInt("soundoff") == 1, + result.getInt("showroof") == 1, + result.getInt("autoscreenshot") == 1, + result.getInt("combatwindow") == 1); + + save.setAppearance((byte) result.getInt("haircolour"), + (byte) result.getInt("topcolour"), + (byte) result.getInt("trousercolour"), + (byte) result.getInt("skincolour"), + (byte) result.getInt("headsprite"), + (byte) result.getInt("bodysprite"), + result.getInt("male") == 1, result.getInt("skulled")); + + save.setQuestPoints(result.getInt("quest_points")); + + save.setExp(intArrayFromStringArray(Statements.playerExp, "exp_", + Config.statArray, user)); + save.setCurStats(intArrayFromStringArray(Statements.playerCurExp, + "cur_", Config.statArray, user)); + result = resultSetFromLongs(Statements.playerInvItems, user); + while (result.next()) { + save.addInvItem(result.getInt("id"), result.getInt("amount"), + result.getInt("wielded") == 1); + } + + result = resultSetFromLongs(Statements.playerBankItems, user); + while (result.next()) { + save.addBankItem(result.getInt("id"), result.getInt("amount")); + } + + save.addFriends(longListFromResultSet( + resultSetFromLongs(Statements.playerFriends, user), + "friend")); + save.addIgnore(longListFromResultSet( + resultSetFromLongs(Statements.playerIngored, user), + "ignore")); + + result = resultSetFromLongs(Statements.playerQuests, user); + while (result.next()) { + save.setQuestStage(result.getInt("id"), result.getInt("stage")); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return save; + } + + private void updateLongs(String statement, long... longA) { + PreparedStatement prepared = null; + try { + prepared = conn.prepareStatement(statement); + + for (int i = 1; i <= longA.length; i++) { + prepared.setLong(i, longA[i - 1]); + } + + prepared.executeUpdate(); + } catch (SQLException e) { + if (prepared != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + statement); + } + } + + private void updateIntsLongs(String statement, int[] intA, long[] longA) { + PreparedStatement prepared = null; + try { + prepared = conn.prepareStatement(statement); + + for (int i = 1; i <= intA.length; i++) { + prepared.setInt(i, intA[i - 1]); + } + int offset = intA.length + 1; + for (int i = 0; i < longA.length; i++) { + prepared.setLong(i + offset, longA[i]); + } + + prepared.executeUpdate(); + } catch (SQLException e) { + if (prepared != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + statement); + } + } + + private int[] intArrayFromStringArray(String statement, String prefix, + String[] stringArray, long... args) { + ResultSet result = resultSetFromLongs(statement, args); + + try { + result.next(); + } catch (SQLException e1) { + e1.printStackTrace(); + return null; + } + + int[] data = new int[stringArray.length]; + + for (int i = 0; i < data.length; i++) { + try { + data[i] = result.getInt(prefix + stringArray[i]); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } + } + return data; + } + + private List longListFromResultSet(ResultSet result, String param) + throws SQLException { + List list = new ArrayList(); + + while (result.next()) { + list.add(result.getLong(param)); + } + + return list; + } + + private ResultSet resultSetFromLongs(String statement, long... longA) { + PreparedStatement prepared = null; + ResultSet result = null; + try { + prepared = conn.prepareStatement(statement); + + for (int i = 1; i <= longA.length; i++) { + prepared.setLong(i, longA[i - 1]); + } + + result = prepared.executeQuery(); + } catch (SQLException e) { + if (prepared != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + statement); + } + + return result; + } + + private boolean hasNextFromLongs(String statement, long... longA) { + PreparedStatement prepared = null; + ResultSet result = null; + try { + prepared = conn.prepareStatement(statement); + + for (int i = 1; i <= longA.length; i++) { + prepared.setLong(i, longA[i - 1]); + } + + result = prepared.executeQuery(); + } catch (SQLException e) { + if (prepared != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + statement); + } + + try { + return result.next(); + } catch (Exception e) { + return false; + } + } + + public class Statements { + private static final String PREFIX = "pk_"; + private static final String logTrade = "INSERT `" + PREFIX + + "_tradelog` VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; + private static final String logReport = "INSERT INTO `" + + PREFIX + + "reports`(`from`, `about`, `time`, `reason`, `x`, `y`, `status`) VALUES(?, ?, ?, ?, ?, ?, ?)"; + private static final String resetOnlineFlag = "UPDATE `" + PREFIX + + "players` SET online=0, world=-1 WHERE world=?"; + private static final String logKill = "INSERT INTO `" + PREFIX + + "kills`(`user`, `killed`, `time`, `type`) VALUES(?, ?, ?, ?)"; + private static final String addFriend = "INSERT INTO `" + PREFIX + + "friends`(`user`, `friend`) VALUES(?, ?)"; + private static final String addFriend_isOnline0 = "SELECT 1 FROM `" + + PREFIX + + "players` AS p LEFT JOIN `" + + PREFIX + + "friends` AS f ON f.user=p.user WHERE (p.block_private=0 OR f.friend=?) AND p.user=?"; + private static final String addFriend_isOnline1 = "SELECT 1 FROM `" + + PREFIX + + "players` AS p LEFT JOIN `" + + PREFIX + + "friends` AS f ON f.friend=p.user WHERE p.block_private=1 AND f.user=? AND p.user=?"; + private static final String removeFriend = "DELETE FROM `" + PREFIX + + "friends` WHERE `user` LIKE ? AND `friend` LIKE ?"; + private static final String removeFriend_isOnline = "SELECT 1 FROM `" + + PREFIX + "players` WHERE block_private=1 AND user=?"; + private static final String addIgnore = "INSERT INTO `" + PREFIX + + "ignores`(`user`, `ignore`) VALUES(?, ?)"; + private static final String removeIgnore = "DELETE FROM `" + PREFIX + + "ignores` WHERE `user` LIKE ? AND `ignore` LIKE ?"; + private static final String friendsList0 = "SELECT p.user FROM `" + + PREFIX + + "friends` AS f INNER JOIN `" + + PREFIX + + "players` AS p ON p.user=f.friend WHERE p.block_private=0 AND f.user=?"; + private static final String friendsList1 = "SELECT user FROM `" + + PREFIX + "friends` WHERE friend=?"; + private static final String chatBlock = "UPDATE `" + PREFIX + + "players` SET block_chat=? WHERE user=?"; + private static final String privateBlock = "UPDATE `" + PREFIX + + "players` SET block_private=? WHERE user=?"; + private static final String privateBlock_online = "SELECT user FROM `" + + PREFIX + + "friends` WHERE friend=? AND user NOT IN (SELECT friend FROM `" + + PREFIX + "friends` WHERE user=?)"; + private static final String tradeBlock = "UPDATE `" + PREFIX + + "players` SET block_trade=? WHERE user=?"; + private static final String duelBlock = "UPDATE `pk_players` SET block_duel=? WHERE user=?"; + private static final String basicInfo = "SELECT banned, owner, group_id FROM `" + + PREFIX + "players` WHERE `user` = ?"; + private static final String setOnlineFlag = "UPDATE `" + PREFIX + + "players` SET online=1, world=? WHERE user=?"; + private static final String setBanned = "UPDATE `" + PREFIX + + "players` SET `banned`=? WHERE `user` = ?"; + private static final String logBan = "INSERT `" + PREFIX + + "banlog` VALUES(?, ?, ?)"; + private static final String playerData = "SELECT * FROM `" + PREFIX + + "players` WHERE `user`=?"; + private static final String playerExp = "SELECT * FROM `" + PREFIX + + "experience` WHERE `user`=?"; + private static final String playerCurExp = "SELECT * FROM `" + PREFIX + + "curstats` WHERE `user`=?"; + private static final String playerInvItems = "SELECT id,amount,wielded FROM `" + + PREFIX + "invitems` WHERE `user`=? ORDER BY `slot` ASC"; + private static final String playerBankItems = "SELECT id,amount FROM `" + + PREFIX + "bank` WHERE `user`=? ORDER BY `slot` ASC"; + private static final String playerFriends = "SELECT friend FROM `" + + PREFIX + "friends` WHERE `user`=?"; + private static final String playerIngored = "SELECT `ignore` FROM `" + + PREFIX + "ignores` WHERE `user`=?"; + private static final String playerQuests = "SELECT * FROM `" + PREFIX + + "quests` WHERE `user`=?"; + private static final String save_DeleteBank = "DELETE FROM `" + PREFIX + + "bank` WHERE `user`=?"; + private static final String save_AddBank = "INSERT INTO `" + PREFIX + + "bank`(`user`, `id`, `amount`, `slot`) VALUES(?, ?, ?, ?)"; + private static final String save_DeleteInv = "DELETE FROM `" + PREFIX + + "invitems` WHERE `user`=?"; + private static final String save_AddInvItem = "INSERT INTO `" + + PREFIX + + "invitems`(`user`, `id`, `amount`, `wielded`, `slot`) VALUES(?, ?, ?, ?, ?)"; + private static final String save_UpdateBasicInfo = "UPDATE `" + + PREFIX + + "players` SET `combat`=?, skill_total=?, `x`=?, `y`=?, `fatigue`=?, `haircolour`=?, `topcolour`=?, `trousercolour`=?, `skincolour`=?, `headsprite`=?, `bodysprite`=?, `male`=?, `skulled`=?, `combatstyle`=?, `quest_points`=? WHERE `user`=?"; + private static final String save_DeleteQuests = "DELETE FROM `" + + PREFIX + "quests` WHERE `user`=?"; + private static final String save_AddQuest = "INSERT INTO `" + PREFIX + + "quests` (`user`, `id`, `stage`) VALUES(?, ?, ?)"; + private static final String save_SetEventCD = "UPDATE `" + PREFIX + + "players` SET eventcd=? WHERE user=?"; + private static final String logLogin = "INSERT INTO `pk_logins`(`user`, `time`, `ip`) VALUES(?, ?, ?)"; + private static final String logIn = "UPDATE `pk_players` SET login_date=?, login_ip=? WHERE user=?"; + } + + @Override + public void logLogin(long user, String ip) { + PreparedStatement logLogin = null; + try { + logLogin = conn.prepareStatement(Statements.logLogin); + + logLogin.setLong(1, user); + logLogin.setLong(2, System.currentTimeMillis() / 1000); + logLogin.setString(3, ip); + + logLogin.executeUpdate(); + } catch (SQLException e) { + if (logLogin != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + Statements.logLogin); + + } + } + + @Override + public void logIn(String ip, long user) { + PreparedStatement login = null; + try { + login = conn.prepareStatement(Statements.logIn); + + login.setLong(1, System.currentTimeMillis() / 1000); + login.setString(2, ip); + login.setLong(3, user); + + login.executeUpdate(); + } catch (SQLException e) { + if (login != null) + e.printStackTrace(); + else + System.out.println("Failed to create prepared statement: " + + Statements.logIn); + + } + } +} diff --git a/LoginServer/src/org/moparscape/msc/ls/util/Config.java b/LoginServer/src/org/moparscape/msc/ls/util/Config.java index 245c1cc..7e57eae 100644 --- a/LoginServer/src/org/moparscape/msc/ls/util/Config.java +++ b/LoginServer/src/org/moparscape/msc/ls/util/Config.java @@ -10,55 +10,66 @@ import java.io.IOException; import java.util.Properties; public class Config { - public static int LS_PORT, QUERY_PORT; + public static String STORAGE_MEDIUM; - public static String RSCDLS_HOME, CONF_DIR, LOG_DIR, MYSQL_HOST, MYSQL_DB, MYSQL_USER, MYSQL_PASS, LS_IP, QUERY_IP, AUTH_URL; + public static int LS_PORT, QUERY_PORT; - public static long START_TIME; + public static String RSCDLS_HOME, CONF_DIR, LOG_DIR, MYSQL_HOST, MYSQL_DB, + MYSQL_USER, MYSQL_PASS, LS_IP, QUERY_IP, AUTH_URL; - static { - loadEnv(); - } + public static long START_TIME; - /** - * Called to load config settings from the given file - * - * @param file - * the xml file to load settings from - * @throws IOException - * if an i/o error occurs - */ - public static void initConfig(String file) throws IOException { - START_TIME = System.currentTimeMillis(); - - Properties props = new Properties(); - props.loadFromXML(new FileInputStream(file)); - - MYSQL_HOST = props.getProperty("mysqlhost"); - MYSQL_DB = props.getProperty("mysqldb"); - MYSQL_USER = props.getProperty("mysqluser"); - MYSQL_PASS = props.getProperty("mysqlpass"); - - LS_IP = props.getProperty("lsip"); - LS_PORT = Integer.parseInt(props.getProperty("lsport")); - QUERY_IP = props.getProperty("queryip"); - QUERY_PORT = Integer.parseInt(props.getProperty("queryport")); - AUTH_URL = props.getProperty("authURL", "https://www.moparscape.org/auth.php?field="); - - props.clear(); - } - - /** - * Called to load RSCDLS_HOME and CONF_DIR Used to be situated in - * PersistenceManager - */ - private static void loadEnv() { - String home = System.getenv("RSCDLS_HOME"); - if (home == null) { // the env var hasnt been set, fall back to . - home = "."; + static { + loadEnv(); } - CONF_DIR = home + File.separator + "conf"; - LOG_DIR = home + File.separator + "logs"; - RSCDLS_HOME = home; - } + + /** + * Called to load config settings from the given file + * + * @param file + * the xml file to load settings from + * @throws IOException + * if an i/o error occurs + */ + public static void initConfig(String file) throws IOException { + START_TIME = System.currentTimeMillis(); + + Properties props = new Properties(); + props.loadFromXML(new FileInputStream(file)); + + MYSQL_HOST = props.getProperty("mysqlhost"); + MYSQL_DB = props.getProperty("mysqldb"); + MYSQL_USER = props.getProperty("mysqluser"); + MYSQL_PASS = props.getProperty("mysqlpass"); + + LS_IP = props.getProperty("lsip"); + LS_PORT = Integer.parseInt(props.getProperty("lsport")); + QUERY_IP = props.getProperty("queryip"); + QUERY_PORT = Integer.parseInt(props.getProperty("queryport")); + AUTH_URL = props.getProperty("authURL", + "https://www.moparscape.org/auth.php?field="); + STORAGE_MEDIUM = props.getProperty("storage-medium", + "org.moparscape.msc.ls.persistence.impl.MySQL"); + + props.clear(); + } + + /** + * Called to load RSCDLS_HOME and CONF_DIR Used to be situated in + * PersistenceManager + */ + private static void loadEnv() { + String home = System.getenv("RSCDLS_HOME"); + if (home == null) { // the env var hasnt been set, fall back to . + home = "."; + } + CONF_DIR = home + File.separator + "conf"; + LOG_DIR = home + File.separator + "logs"; + RSCDLS_HOME = home; + } + + public static final String[] statArray = { "attack", "defense", "strength", + "hits", "ranged", "prayer", "magic", "cooking", "woodcut", + "fletching", "fishing", "firemaking", "crafting", "smithing", + "mining", "herblaw", "agility", "thieving" }; } diff --git a/README b/README index 01ebb45..d679320 100644 --- a/README +++ b/README @@ -1 +1,22 @@ -An emulator for an old java MMORPG. \ No newline at end of file +An emulator for an old java MMORPG. + +Setup +====== +Install the JRE and JDK +Install Ant +Install Ivy +Install MySQL + +Ensure all the paths are set correctly. + +Import Database.sql + +If you have any questions regarding that use Google. + +Go to LoginServer in the terminal/command prompt and type-- +ant runls + +Go to GameServer in the terminal/command prompy and type-- +ant run + +You're now ready to start accept connections.