Search in sources :

Example 1 with Channel

use of net.server.channel.Channel in project HeavenMS by ronancpl.

the class DueyHandler method handlePacket.

@Override
public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
    if (!ServerConstants.USE_DUEY) {
        c.announce(MaplePacketCreator.enableActions());
        return;
    }
    byte operation = slea.readByte();
    if (operation == Actions.TOSERVER_SEND_ITEM.getCode()) {
        final int fee = 5000;
        byte inventId = slea.readByte();
        short itemPos = slea.readShort();
        short amount = slea.readShort();
        int mesos = slea.readInt();
        String recipient = slea.readMapleAsciiString();
        if (mesos < 0 || ((long) mesos + fee + getFee(mesos)) > Integer.MAX_VALUE || (amount < 1 && mesos == 0)) {
            AutobanFactory.PACKET_EDIT.alert(c.getPlayer(), c.getPlayer().getName() + " tried to packet edit with duey.");
            FilePrinter.printError(FilePrinter.EXPLOITS + c.getPlayer().getName() + ".txt", c.getPlayer().getName() + " tried to use duey with mesos " + mesos + " and amount " + amount + "\r\n");
            c.disconnect(true, false);
            return;
        }
        int finalcost = mesos + fee + getFee(mesos);
        boolean send = false;
        if (c.getPlayer().getMeso() >= finalcost) {
            int accid = getAccIdFromCNAME(recipient, true);
            if (accid != -1) {
                if (accid != c.getAccID()) {
                    send = true;
                } else {
                    c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_SEND_SAMEACC_ERROR.getCode()));
                }
            } else {
                c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_SEND_NAME_DOES_NOT_EXIST.getCode()));
            }
        } else {
            c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_SEND_NOT_ENOUGH_MESOS.getCode()));
        }
        MapleClient rClient = null;
        int channel = c.getWorldServer().find(recipient);
        if (channel > -1) {
            Channel rcserv = c.getWorldServer().getChannel(channel);
            rClient = rcserv.getPlayerStorage().getCharacterByName(recipient).getClient();
        }
        if (send) {
            if (inventId > 0) {
                MapleInventoryType inv = MapleInventoryType.getByType(inventId);
                Item item = c.getPlayer().getInventory(inv).getItem(itemPos);
                if (item != null && c.getPlayer().getItemQuantity(item.getItemId(), false) >= amount) {
                    c.getPlayer().gainMeso(-finalcost, false);
                    c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_SEND_SUCCESSFULLY_SENT.getCode()));
                    if (ItemConstants.isRechargable(item.getItemId())) {
                        MapleInventoryManipulator.removeFromSlot(c, inv, itemPos, item.getQuantity(), true);
                    } else {
                        MapleInventoryManipulator.removeFromSlot(c, inv, itemPos, amount, true, false);
                    }
                    addItemToDB(item, amount, mesos, c.getPlayer().getName(), getAccIdFromCNAME(recipient, false));
                } else {
                    if (item != null) {
                        c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_SEND_INCORRECT_REQUEST.getCode()));
                    }
                    return;
                }
            } else {
                c.getPlayer().gainMeso(-finalcost, false);
                c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_SEND_SUCCESSFULLY_SENT.getCode()));
                addMesoToDB(mesos, c.getPlayer().getName(), getAccIdFromCNAME(recipient, false));
            }
            if (rClient != null && rClient.isLoggedIn() && !rClient.getPlayer().isAwayFromWorld()) {
                showDueyNotification(rClient, rClient.getPlayer());
            }
        }
    } else if (operation == Actions.TOSERVER_REMOVE_PACKAGE.getCode()) {
        int packageid = slea.readInt();
        removeItemFromDB(packageid);
        c.announce(MaplePacketCreator.removeItemFromDuey(true, packageid));
    } else if (operation == Actions.TOSERVER_CLAIM_PACKAGE.getCode()) {
        int packageid = slea.readInt();
        List<DueyPackages> packages = new LinkedList<>();
        DueyPackages dp = null;
        Connection con = null;
        try {
            con = DatabaseConnection.getConnection();
            DueyPackages dueypack;
            try (PreparedStatement ps = con.prepareStatement("SELECT * FROM dueypackages LEFT JOIN dueyitems USING (PackageId) WHERE PackageId = ?")) {
                ps.setInt(1, packageid);
                try (ResultSet rs = ps.executeQuery()) {
                    dueypack = null;
                    if (rs.next()) {
                        dueypack = getItemByPID(rs);
                        dueypack.setSender(rs.getString("SenderName"));
                        dueypack.setMesos(rs.getInt("Mesos"));
                        dueypack.setSentTime(rs.getString("TimeStamp"));
                        packages.add(dueypack);
                    }
                }
            }
            dp = dueypack;
            if (dp == null) {
                c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_UNKNOWN_ERROR.getCode()));
                FilePrinter.printError(FilePrinter.EXPLOITS + c.getPlayer().getName() + ".txt", c.getPlayer().getName() + " tried to receive package from duey with id " + packageid + "\r\n");
                return;
            }
            if (dp.getItem() != null) {
                if (!MapleInventoryManipulator.checkSpace(c, dp.getItem().getItemId(), dp.getItem().getQuantity(), dp.getItem().getOwner())) {
                    int itemid = dp.getItem().getItemId();
                    if (MapleItemInformationProvider.getInstance().isPickupRestricted(itemid) && c.getPlayer().getInventory(ItemConstants.getInventoryType(itemid)).findById(itemid) != null) {
                        c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_RECEIVER_WITH_UNIQUE.getCode()));
                    } else {
                        c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_NO_FREE_SLOTS.getCode()));
                    }
                    return;
                } else {
                    MapleInventoryManipulator.addFromDrop(c, dp.getItem(), false);
                }
            }
            long gainmesos = 0;
            long totalmesos = (long) dp.getMesos() + (long) c.getPlayer().getMeso();
            if (totalmesos < 0 || dp.getMesos() < 0)
                gainmesos = 0;
            else {
                totalmesos = Math.min(totalmesos, Integer.MAX_VALUE);
                gainmesos = totalmesos - c.getPlayer().getMeso();
            }
            c.getPlayer().gainMeso((int) gainmesos, false);
            removeItemFromDB(packageid);
            c.announce(MaplePacketCreator.removeItemFromDuey(false, packageid));
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Also used : SQLException(java.sql.SQLException) Channel(net.server.channel.Channel) DatabaseConnection(tools.DatabaseConnection) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) LinkedList(java.util.LinkedList) Item(client.inventory.Item) DueyPackages(server.DueyPackages) MapleInventoryType(client.inventory.MapleInventoryType) ResultSet(java.sql.ResultSet) MapleClient(client.MapleClient)

Example 2 with Channel

use of net.server.channel.Channel 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 3 with Channel

use of net.server.channel.Channel 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 4 with Channel

use of net.server.channel.Channel in project HeavenMS by ronancpl.

the class World method shutdown.

public final void shutdown() {
    for (Channel ch : getChannels()) {
        ch.shutdown();
    }
    if (petsSchedule != null) {
        petsSchedule.cancel(false);
        petsSchedule = null;
    }
    if (mountsSchedule != null) {
        mountsSchedule.cancel(false);
        mountsSchedule = null;
    }
    players.disconnectAll();
}
Also used : Channel(net.server.channel.Channel)

Example 5 with Channel

use of net.server.channel.Channel in project HeavenMS by ronancpl.

the class ServerStatusRequestHandler method handlePacket.

@Override
public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
    // Wuuu? ):
    byte world = (byte) slea.readShort();
    int status;
    int num = 0;
    for (Channel ch : Server.getInstance().getWorld(world).getChannels()) {
        num += ch.getConnectedClients();
    }
    if (num >= ServerConstants.CHANNEL_LOAD) {
        status = 2;
    } else if (num >= ServerConstants.CHANNEL_LOAD * .8) {
        // More than 80 percent o___o
        status = 1;
    } else {
        status = 0;
    }
    c.announce(MaplePacketCreator.getServerStatus(status));
}
Also used : Channel(net.server.channel.Channel)

Aggregations

Channel (net.server.channel.Channel)13 SQLException (java.sql.SQLException)8 Connection (java.sql.Connection)6 PreparedStatement (java.sql.PreparedStatement)6 DatabaseConnection (tools.DatabaseConnection)6 MapleCharacter (client.MapleCharacter)5 Item (client.inventory.Item)5 Point (java.awt.Point)4 IOException (java.io.IOException)4 ResultSet (java.sql.ResultSet)4 UnknownHostException (java.net.UnknownHostException)3 SpawnPoint (server.life.SpawnPoint)3 MapleMap (server.maps.MapleMap)3 MapleMapItem (server.maps.MapleMapItem)3 MapleInventoryType (client.inventory.MapleInventoryType)2 Properties (java.util.Properties)2 Server (net.server.Server)2 World (net.server.world.World)2 MapleEvent (server.events.gm.MapleEvent)2 MapleMonster (server.life.MapleMonster)2