Search in sources :

Example 6 with World

use of net.server.world.World in project HeavenMS by ronancpl.

the class Server method run.

@Override
public void run() {
    Properties p = new Properties();
    try {
        p.load(new FileInputStream("world.ini"));
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Please start create_server.bat");
        System.exit(0);
    }
    System.out.println("HeavenMS v" + ServerConstants.VERSION + " starting up.\r\n");
    if (ServerConstants.SHUTDOWNHOOK)
        Runtime.getRuntime().addShutdownHook(new Thread(shutdown(false)));
    Connection c = null;
    try {
        c = DatabaseConnection.getConnection();
        PreparedStatement ps = c.prepareStatement("UPDATE accounts SET loggedin = 0");
        ps.executeUpdate();
        ps.close();
        ps = c.prepareStatement("UPDATE characters SET HasMerchant = 0");
        ps.executeUpdate();
        ps.close();
        loadCouponRates(c);
        updateActiveCoupons();
        c.close();
    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }
    IoBuffer.setUseDirectBuffer(false);
    IoBuffer.setAllocator(new SimpleBufferAllocator());
    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("codec", (IoFilter) new ProtocolCodecFilter(new MapleCodecFactory()));
    TimerManager tMan = TimerManager.getInstance();
    tMan.start();
    // Purging ftw...
    tMan.register(tMan.purge(), ServerConstants.PURGING_INTERVAL);
    disconnectIdlesOnLoginTask();
    long timeLeft = getTimeLeftForNextHour();
    tMan.register(new CouponWorker(), ServerConstants.COUPON_INTERVAL, timeLeft);
    tMan.register(new RankingWorker(), ServerConstants.RANKING_INTERVAL, timeLeft);
    long timeToTake = System.currentTimeMillis();
    SkillFactory.loadAllSkills();
    System.out.println("Skills loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds");
    timeToTake = System.currentTimeMillis();
    // MapleItemInformationProvider.getInstance().getAllItems(); //unused, rofl
    CashItemFactory.getSpecialCashItems();
    System.out.println("Items loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds");
    timeToTake = System.currentTimeMillis();
    MapleQuest.loadAllQuest();
    System.out.println("Quest loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds\r\n");
    NewYearCardRecord.startPendingNewYearCardRequests();
    if (ServerConstants.USE_THREAD_TRACKER)
        ThreadTracker.getInstance().registerThreadTrackerTask();
    try {
        Integer worldCount = Math.min(ServerConstants.WORLD_NAMES.length, Integer.parseInt(p.getProperty("worlds")));
        for (int i = 0; i < worldCount; i++) {
            System.out.println("Starting world " + i);
            World world = new World(i, Integer.parseInt(p.getProperty("flag" + i)), p.getProperty("eventmessage" + i), ServerConstants.EXP_RATE, ServerConstants.DROP_RATE, ServerConstants.MESO_RATE, ServerConstants.QUEST_RATE);
            worldRecommendedList.add(new Pair<>(i, p.getProperty("whyamirecommended" + i)));
            worlds.add(world);
            channels.add(new HashMap<Integer, String>());
            for (int j = 0; j < Integer.parseInt(p.getProperty("channels" + i)); j++) {
                int channelid = j + 1;
                Channel channel = new Channel(i, channelid);
                world.addChannel(channel);
                channels.get(i).put(channelid, channel.getIP());
            }
            world.setServerMessage(p.getProperty("servermessage" + i));
            System.out.println("Finished loading world " + i + "\r\n");
        }
    } catch (Exception e) {
        // For those who get errors
        e.printStackTrace();
        System.out.println("Error in moople.ini, start CreateINI.bat to re-make the file.");
        System.exit(0);
    }
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
    acceptor.setHandler(new MapleServerHandler());
    try {
        acceptor.bind(new InetSocketAddress(8484));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    System.out.println("Listening on port 8484\r\n\r\n");
    System.out.println("HeavenMS is now online.\r\n");
    online = true;
}
Also used : MapleCodecFactory(net.mina.MapleCodecFactory) SQLException(java.sql.SQLException) InetSocketAddress(java.net.InetSocketAddress) SimpleBufferAllocator(org.apache.mina.core.buffer.SimpleBufferAllocator) Properties(java.util.Properties) ProtocolCodecFilter(org.apache.mina.filter.codec.ProtocolCodecFilter) World(net.server.world.World) NioSocketAcceptor(org.apache.mina.transport.socket.nio.NioSocketAcceptor) RankingWorker(net.server.worker.RankingWorker) CouponWorker(net.server.worker.CouponWorker) Channel(net.server.channel.Channel) Connection(java.sql.Connection) DatabaseConnection(tools.DatabaseConnection) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) TimerManager(server.TimerManager) FileInputStream(java.io.FileInputStream) SQLException(java.sql.SQLException) IOException(java.io.IOException) MapleServerHandler(net.MapleServerHandler)

Example 7 with World

use of net.server.world.World in project HeavenMS by ronancpl.

the class Server method shutdown.

public final Runnable shutdown(final boolean restart) {
    // no player should be online when trying to shutdown!
    return new Runnable() {

        @Override
        public void run() {
            srvLock.lock();
            try {
                System.out.println((restart ? "Restarting" : "Shutting down") + " the server!\r\n");
                // already shutdown
                if (getWorlds() == null)
                    return;
                for (World w : getWorlds()) {
                    w.shutdown();
                }
                if (ServerConstants.USE_THREAD_TRACKER)
                    ThreadTracker.getInstance().cancelThreadTrackerTask();
                TimerManager.getInstance().purge();
                TimerManager.getInstance().stop();
                for (Channel ch : getAllChannels()) {
                    while (!ch.finishedShutdown()) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ie) {
                            ie.printStackTrace();
                            System.err.println("FUCK MY LIFE");
                        }
                    }
                }
                worlds.clear();
                worlds = null;
                channels.clear();
                channels = null;
                worldRecommendedList.clear();
                worldRecommendedList = null;
                System.out.println("Worlds + Channels are offline.");
                acceptor.unbind();
                acceptor = null;
                if (!restart) {
                    System.exit(0);
                } else {
                    System.out.println("\r\nRestarting the server....\r\n");
                    try {
                        // FUU I CAN AND IT'S FREE
                        instance.finalize();
                    } catch (Throwable ex) {
                        ex.printStackTrace();
                    }
                    instance = null;
                    System.gc();
                    // DID I DO EVERYTHING?! D:
                    getInstance().run();
                }
            } finally {
                srvLock.unlock();
            }
        }
    };
}
Also used : Channel(net.server.channel.Channel) World(net.server.world.World)

Example 8 with World

use of net.server.world.World in project HeavenMS by ronancpl.

the class BuddylistModifyHandler method handlePacket.

@Override
public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
    int mode = slea.readByte();
    MapleCharacter player = c.getPlayer();
    BuddyList buddylist = player.getBuddylist();
    if (mode == 1) {
        // add
        String addName = slea.readMapleAsciiString();
        String group = slea.readMapleAsciiString();
        if (group.length() > 16 || addName.length() < 4 || addName.length() > 13) {
            // hax.
            return;
        }
        BuddylistEntry ble = buddylist.get(addName);
        if (ble != null && !ble.isVisible() && group.equals(ble.getGroup())) {
            c.announce(MaplePacketCreator.serverNotice(1, "You already have \"" + ble.getName() + "\" on your Buddylist"));
        } else if (buddylist.isFull() && ble == null) {
            c.announce(MaplePacketCreator.serverNotice(1, "Your buddylist is already full"));
        } else if (ble == null) {
            try {
                World world = c.getWorldServer();
                CharacterIdNameBuddyCapacity charWithId;
                int channel;
                MapleCharacter otherChar = c.getChannelServer().getPlayerStorage().getCharacterByName(addName);
                if (otherChar != null) {
                    channel = c.getChannel();
                    charWithId = new CharacterIdNameBuddyCapacity(otherChar.getId(), otherChar.getName(), otherChar.getBuddylist().getCapacity());
                } else {
                    channel = world.find(addName);
                    charWithId = getCharacterIdAndNameFromDatabase(addName);
                }
                if (charWithId != null) {
                    BuddyAddResult buddyAddResult = null;
                    if (channel != -1) {
                        buddyAddResult = world.requestBuddyAdd(addName, c.getChannel(), player.getId(), player.getName());
                    } else {
                        Connection con = DatabaseConnection.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) as buddyCount FROM buddies WHERE characterid = ? AND pending = 0");
                        ps.setInt(1, charWithId.getId());
                        ResultSet rs = ps.executeQuery();
                        if (!rs.next()) {
                            throw new RuntimeException("Result set expected");
                        } else if (rs.getInt("buddyCount") >= charWithId.getBuddyCapacity()) {
                            buddyAddResult = BuddyAddResult.BUDDYLIST_FULL;
                        }
                        rs.close();
                        ps.close();
                        ps = con.prepareStatement("SELECT pending FROM buddies WHERE characterid = ? AND buddyid = ?");
                        ps.setInt(1, charWithId.getId());
                        ps.setInt(2, player.getId());
                        rs = ps.executeQuery();
                        if (rs.next()) {
                            buddyAddResult = BuddyAddResult.ALREADY_ON_LIST;
                        }
                        rs.close();
                        ps.close();
                        con.close();
                    }
                    if (buddyAddResult == BuddyAddResult.BUDDYLIST_FULL) {
                        c.announce(MaplePacketCreator.serverNotice(1, "\"" + addName + "\"'s Buddylist is full"));
                    } else {
                        int displayChannel;
                        displayChannel = -1;
                        int otherCid = charWithId.getId();
                        if (buddyAddResult == BuddyAddResult.ALREADY_ON_LIST && channel != -1) {
                            displayChannel = channel;
                            notifyRemoteChannel(c, channel, otherCid, ADDED);
                        } else if (buddyAddResult != BuddyAddResult.ALREADY_ON_LIST && channel == -1) {
                            Connection con = DatabaseConnection.getConnection();
                            try (PreparedStatement ps = con.prepareStatement("INSERT INTO buddies (characterid, `buddyid`, `pending`) VALUES (?, ?, 1)")) {
                                ps.setInt(1, charWithId.getId());
                                ps.setInt(2, player.getId());
                                ps.executeUpdate();
                            }
                            con.close();
                        }
                        buddylist.put(new BuddylistEntry(charWithId.getName(), group, otherCid, displayChannel, true));
                        c.announce(MaplePacketCreator.updateBuddylist(buddylist.getBuddies()));
                    }
                } else {
                    c.announce(MaplePacketCreator.serverNotice(1, "A character called \"" + addName + "\" does not exist"));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            ble.changeGroup(group);
            c.announce(MaplePacketCreator.updateBuddylist(buddylist.getBuddies()));
        }
    } else if (mode == 2) {
        // accept buddy
        int otherCid = slea.readInt();
        if (!buddylist.isFull()) {
            try {
                // worldInterface.find(otherCid);
                int channel = c.getWorldServer().find(otherCid);
                String otherName = null;
                MapleCharacter otherChar = c.getChannelServer().getPlayerStorage().getCharacterById(otherCid);
                if (otherChar == null) {
                    Connection con = DatabaseConnection.getConnection();
                    try (PreparedStatement ps = con.prepareStatement("SELECT name FROM characters WHERE id = ?")) {
                        ps.setInt(1, otherCid);
                        try (ResultSet rs = ps.executeQuery()) {
                            if (rs.next()) {
                                otherName = rs.getString("name");
                            }
                        }
                    }
                    con.close();
                } else {
                    otherName = otherChar.getName();
                }
                if (otherName != null) {
                    buddylist.put(new BuddylistEntry(otherName, "Default Group", otherCid, channel, true));
                    c.announce(MaplePacketCreator.updateBuddylist(buddylist.getBuddies()));
                    notifyRemoteChannel(c, channel, otherCid, ADDED);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        nextPendingRequest(c);
    } else if (mode == 3) {
        // delete
        int otherCid = slea.readInt();
        player.deleteBuddy(otherCid);
    }
}
Also used : BuddyAddResult(client.BuddyList.BuddyAddResult) MapleCharacter(client.MapleCharacter) SQLException(java.sql.SQLException) DatabaseConnection(tools.DatabaseConnection) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) BuddyList(client.BuddyList) World(net.server.world.World) BuddylistEntry(client.BuddylistEntry) ResultSet(java.sql.ResultSet)

Example 9 with World

use of net.server.world.World in project HeavenMS by ronancpl.

the class WhisperHandler method handlePacket.

public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
    byte mode = slea.readByte();
    if (mode == 6) {
        // whisper
        String recipient = slea.readMapleAsciiString();
        String text = slea.readMapleAsciiString();
        MapleCharacter player = c.getChannelServer().getPlayerStorage().getCharacterByName(recipient);
        if (c.getPlayer().getAutobanManager().getLastSpam(7) + 200 > System.currentTimeMillis()) {
            return;
        }
        if (text.length() > Byte.MAX_VALUE && !player.isGM()) {
            AutobanFactory.PACKET_EDIT.alert(c.getPlayer(), c.getPlayer().getName() + " tried to packet edit with whispers.");
            FilePrinter.printError(FilePrinter.EXPLOITS + c.getPlayer().getName() + ".txt", c.getPlayer().getName() + " tried to send text with length of " + text.length() + "\r\n");
            c.disconnect(true, false);
            return;
        }
        if (player != null) {
            player.getClient().announce(MaplePacketCreator.getWhisper(c.getPlayer().getName(), c.getChannel(), text));
            if (player.isHidden() && player.gmLevel() >= c.getPlayer().gmLevel()) {
                c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 0));
            } else {
                c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 1));
            }
        } else {
            // not found
            World world = c.getWorldServer();
            if (world.isConnected(recipient)) {
                world.whisper(c.getPlayer().getName(), recipient, c.getChannel(), text);
                player = world.getPlayerStorage().getCharacterByName(recipient);
                if (player.isHidden() && player.gmLevel() >= c.getPlayer().gmLevel())
                    c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 0));
                else
                    c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 1));
            } else {
                c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 0));
            }
        }
        c.getPlayer().getAutobanManager().spam(7);
    } else if (mode == 5) {
        // - /find
        String recipient = slea.readMapleAsciiString();
        MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(recipient);
        if (victim != null && c.getPlayer().gmLevel() >= victim.gmLevel()) {
            if (victim.getCashShop().isOpened()) {
                c.announce(MaplePacketCreator.getFindReply(victim.getName(), -1, 2));
            // } else if (victim.inMTS()) {
            // c.announce(MaplePacketCreator.getFindReply(victim.getName(), -1, 0));
            } else {
                c.announce(MaplePacketCreator.getFindReply(victim.getName(), victim.getMap().getId(), 1));
            }
        } else {
            // not found
            try {
                Connection con = DatabaseConnection.getConnection();
                PreparedStatement ps = con.prepareStatement("SELECT gm FROM characters WHERE name = ?");
                ps.setString(1, recipient);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    if (rs.getInt("gm") >= c.getPlayer().gmLevel()) {
                        c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 0));
                        return;
                    }
                }
                rs.close();
                ps.close();
                con.close();
                byte channel = (byte) (c.getWorldServer().find(recipient) - 1);
                if (channel > -1) {
                    c.announce(MaplePacketCreator.getFindReply(recipient, channel, 3));
                } else {
                    c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 0));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    } else if (mode == 0x44) {
    // Buddy find?
    }
}
Also used : MapleCharacter(client.MapleCharacter) SQLException(java.sql.SQLException) DatabaseConnection(tools.DatabaseConnection) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) World(net.server.world.World)

Example 10 with World

use of net.server.world.World in project HeavenMS by ronancpl.

the class Commands method executeHeavenMsCommandLv6.

public static boolean executeHeavenMsCommandLv6(Channel cserv, Server srv, MapleClient c, String[] sub) {
    // Admin
    MapleCharacter player = c.getPlayer();
    MapleCharacter victim;
    switch(sub[0]) {
        case "setgmlevel":
            if (sub.length < 3) {
                player.yellowMessage("Syntax: !setgmlevel <playername> <newlevel>");
                break;
            }
            int newLevel = Integer.parseInt(sub[2]);
            MapleCharacter target = cserv.getPlayerStorage().getCharacterByName(sub[1]);
            if (target != null) {
                target.setGMLevel(newLevel);
                target.getClient().setGMLevel(newLevel);
                target.dropMessage("You are now a level " + newLevel + " GM. See @commands for a list of available commands.");
                player.dropMessage(target + " is now a level " + newLevel + " GM.");
            } else {
                player.dropMessage("Player '" + sub[1] + "' was not found on this channel.");
            }
            break;
        case "warpworld":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !warpworld <worldid>");
                break;
            }
            Server server = Server.getInstance();
            byte worldb = Byte.parseByte(sub[1]);
            if (worldb <= (server.getWorlds().size() - 1)) {
                try {
                    String[] socket = server.getIP(worldb, c.getChannel()).split(":");
                    c.getWorldServer().removePlayer(player);
                    // LOL FORGOT THIS ><
                    player.getMap().removePlayer(player);
                    c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION);
                    player.setWorld(worldb);
                    // To set the new world :O (true because else 2 player instances are created, one in both worlds)
                    player.saveToDB();
                    c.announce(MaplePacketCreator.getChannelChange(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1])));
                } catch (UnknownHostException | NumberFormatException ex) {
                    ex.printStackTrace();
                    player.message("Error when trying to change worlds, are you sure the world you are trying to warp to has the same amount of channels?");
                }
            } else {
                player.message("Invalid world; highest number available: " + (server.getWorlds().size() - 1));
            }
            break;
        case "saveall":
            for (World world : Server.getInstance().getWorlds()) {
                for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
                    chr.saveToDB();
                }
            }
            String message = player.getName() + " used !saveall.";
            Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.serverNotice(5, message));
            player.message("All players saved successfully.");
            break;
        case "dcall":
            for (World world : Server.getInstance().getWorlds()) {
                for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
                    if (!chr.isGM()) {
                        chr.getClient().disconnect(false, false);
                    }
                }
            }
            player.message("All players successfully disconnected.");
            break;
        case "mapplayers":
            String names = "";
            int map = player.getMapId();
            for (World world : Server.getInstance().getWorlds()) {
                for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
                    int curMap = chr.getMapId();
                    String hp = Integer.toString(chr.getHp());
                    String maxhp = Integer.toString(chr.getMaxHp());
                    String name = chr.getName() + ": " + hp + "/" + maxhp;
                    if (map == curMap) {
                        names = names.equals("") ? name : (names + ", " + name);
                    }
                }
            }
            player.message("These b lurkin: " + names);
            break;
        case "getacc":
            if (sub.length < 2) {
                player.yellowMessage("Syntax: !getacc <playername>");
                break;
            }
            victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
            if (victim != null) {
                player.message(victim.getName() + "'s account name is " + victim.getClient().getAccountName() + ".");
            } else {
                player.message("Player '" + sub[1] + "' could not be found on this world.");
            }
            break;
        case "shutdown":
        case "shutdownnow":
            int time = 60000;
            if (sub[0].equals("shutdownnow")) {
                time = 1;
            } else if (sub.length > 1) {
                time *= Integer.parseInt(sub[1]);
            }
            if (time > 1) {
                int seconds = (int) (time / 1000) % 60;
                int minutes = (int) ((time / (1000 * 60)) % 60);
                int hours = (int) ((time / (1000 * 60 * 60)) % 24);
                int days = (int) ((time / (1000 * 60 * 60 * 24)));
                String strTime = "";
                if (days > 0)
                    strTime += days + " days, ";
                if (hours > 0)
                    strTime += hours + " hours, ";
                strTime += minutes + " minutes, ";
                strTime += seconds + " seconds";
                for (World w : Server.getInstance().getWorlds()) {
                    for (MapleCharacter chr : w.getPlayerStorage().getAllCharacters()) {
                        chr.dropMessage("Server is undergoing maintenance process, and will be shutdown in " + strTime + ". Prepare yourself to quit safely in the mean time.");
                    }
                }
            }
            TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
            break;
        case "clearquestcache":
            MapleQuest.clearCache();
            player.dropMessage(5, "Quest Cache Cleared.");
            break;
        case "clearquest":
            if (sub.length < 1) {
                player.dropMessage(5, "Please include a quest ID.");
                break;
            }
            MapleQuest.clearCache(Integer.parseInt(sub[1]));
            player.dropMessage(5, "Quest Cache for quest " + sub[1] + " cleared.");
            break;
        case "fred":
            c.announce(MaplePacketCreator.fredrickMessage(Byte.valueOf(sub[1])));
            break;
        default:
            return false;
    }
    return true;
}
Also used : MapleCharacter(client.MapleCharacter) Server(net.server.Server) UnknownHostException(java.net.UnknownHostException) World(net.server.world.World) Point(java.awt.Point) SpawnPoint(server.life.SpawnPoint)

Aggregations

World (net.server.world.World)18 MapleCharacter (client.MapleCharacter)10 SQLException (java.sql.SQLException)5 Server (net.server.Server)4 MapleMessengerCharacter (net.server.world.MapleMessengerCharacter)4 MaplePartyCharacter (net.server.world.MaplePartyCharacter)4 Connection (java.sql.Connection)3 PreparedStatement (java.sql.PreparedStatement)3 Channel (net.server.channel.Channel)3 MapleParty (net.server.world.MapleParty)3 DatabaseConnection (tools.DatabaseConnection)3 BuddylistEntry (client.BuddylistEntry)2 ResultSet (java.sql.ResultSet)2 MapleGuild (net.server.guild.MapleGuild)2 MapleMessenger (net.server.world.MapleMessenger)2 MapleMap (server.maps.MapleMap)2 BuddyList (client.BuddyList)1 BuddyAddResult (client.BuddyList.BuddyAddResult)1 CharacterNameAndId (client.CharacterNameAndId)1 MapleFamily (client.MapleFamily)1