Мо3олЬ 68 Опубликовано 30 января, 2013 Всем привет)) Вот решил выложить код, автоматической выдачи бонуса L2top для сборки L2jServer (Epilogue)! Ядро ### Eclipse Workspace Patch 1.0 #P L2jEnergy_GameServer Index: java/com/l2jserver/gameserver/GameServer.java =================================================================== --- java/com/l2jserver/gameserver/GameServer.java (revision 3) +++ java/com/l2jserver/gameserver/GameServer.java (working copy) @@ -43,6 +43,7 @@ import com.l2jserver.gameserver.instancemanager.*; import com.l2jserver.gameserver.instancemanager.itemauction.*; import com.l2jserver.gameserver.instancemanager.leaderboards.*; +import com.l2jserver.gameserver.instancemanager.vote.L2TopManager; import com.l2jserver.gameserver.instancemanager.clanhallsiege.*; import com.l2jserver.gameserver.model.AutoChatHandler; import com.l2jserver.gameserver.model.AutoSpawnHandler; @@ -246,6 +247,9 @@ printSection("Auction"); ItemAuctionManager.init(); + printSection("L2Top"); + L2TopManager.getInstance(); + printSection("CursedWeapons"); CursedWeaponsManager.getInstance(); Index: java/com/l2jserver/Config.java =================================================================== --- java/com/l2jserver/Config.java (revision 3) +++ java/com/l2jserver/Config.java (working copy) @@ -71,6 +71,7 @@ public static final String L2JENERGY_COMMANDS = "./config/L2jEnergy/Cmd.properties"; public static final String L2JENERGY_EVENTS = "./config/L2jEnergy/Events.properties"; public static final String L2JENERGY_ITEMS = "./config/L2jEnergy/Items.properties"; + public static final String L2JENERGY_L2TOP_CONFIG_FILE = "./config/L2jEnergy/L2Top.properties"; public static final String L2JENERGY_OTHER = "./config/L2jEnergy/Other.properties"; public static final String L2JENERGY_PVP = "./config/L2jEnergy/PvP.properties"; public static final String L2JENERGY_SECURITY = "./config/L2jEnergy/Security.properties"; @@ -336,6 +337,14 @@ public static int AIOITEM_SCHEME_PROFILE_PRICE; public static int AIOITEM_SCHEME_MAX_PROFILES; public static int AIOITEM_SCHEME_MAX_PROFILE_BUFFS; + public static boolean L2TOP_SERVICE_ENABLED; + public static int L2TOP_INTERVAL; + public static int L2TOP_CLEAN_DAY; + public static int L2_TOP_REWARD_ID; + public static int L2_TOP_REWARD_COUNT; + public static String L2TOP_WEB_ADRESS; + public static String L2TOP_SMS_ADRESS; + public static String L2_TOP_SERVER_ADRES; public static boolean ENABLE_CMD_RECORD; public static boolean ENABLE_PVP_REWARD_SYSTEM; public static int PVP_REWARD_ITEM_ID; @@ -1480,6 +1489,26 @@ throw new Error("Failed to Load " + L2JENERGY_ITEMS + " File."); } + //L2Top + try { + L2Properties L2jEnergyL2TopSettings = new L2Properties(); + is = new FileInputStream(new File(L2JENERGY_L2TOP_CONFIG_FILE)); + L2jEnergyL2TopSettings.load(is); + + L2TOP_SERVICE_ENABLED = Boolean.parseBoolean(L2jEnergyL2TopSettings.getProperty("L2TopServiceEnable", "false")); + L2TOP_INTERVAL = Integer.parseInt(L2jEnergyL2TopSettings.getProperty("L2TopInterval", "5")); + L2TOP_CLEAN_DAY = Integer.parseInt(L2jEnergyL2TopSettings.getProperty("L2TopCleanDays", "30")); + L2_TOP_REWARD_ID = Integer.parseInt(L2jEnergyL2TopSettings.getProperty("L2TopRewardId", "4037")); + L2_TOP_REWARD_COUNT = Integer.parseInt(L2jEnergyL2TopSettings.getProperty("L2TopRewardCount", "1000")); + L2TOP_WEB_ADRESS = L2jEnergyL2TopSettings.getProperty("L2TopWebAddress", ""); + L2TOP_SMS_ADRESS = L2jEnergyL2TopSettings.getProperty("L2TopSmsAddress", ""); + L2_TOP_SERVER_ADRES = L2jEnergyL2TopSettings.getProperty("L2TopServerAddress", ""); + } catch (Exception e) { + e.printStackTrace(); + throw new Error("Failed to Load " + L2JENERGY_L2TOP_CONFIG_FILE + " File."); + } + try { L2Properties L2jEnergyOtherSettings = new L2Properties(); is = new FileInputStream(new File(L2JENERGY_OTHER)); Index: java/config/L2jEnergy/L2Top.properties =================================================================== --- java/config/L2jEnergy/L2Top.properties (revision 0) +++ java/config/L2jEnergy/L2Top.properties (revision 0) @@ -0,0 +1,36 @@ +#===============================================================# +# L2Top: Автоматическая выдача награды за голосование # +#===============================================================# +# # Конектится к топу, получает список, +# заносит в бд, выдает награду онлайн, без всяких нпсов, кнопок на сайте +# без необходимости выходить\заходить чару. +# Поддерживает русские ники. +# Если будут возникать проблемы - очистите файл data\vote.txt +# Вкл/выкл сервис. +# По умолчанию: True +L2TopServiceEnable = False + +# Интервал коннекта к топу и обновления бд (мин) +# По умолчанию: 5 +L2TopInterval = 5 + +# ID награды выдаваемой за голосование +L2TopRewardId = 57 + +# Количество выдаваемой награды +L2TopRewardCount = 1000000 + +# Дней до очистки списка проголосовавших +# По умолчанию: 30 +L2TopCleanDays = 30 + +# Адрес Вашего сервера (без http://) +L2TopServerAddress = + +# Список последних проголосовавших через web интерфейс +# http://l2top.ru/edit...stVotes&uid=Ваш ID_web&key=ключ +L2TopWebAddress = + +# Список последних проголосовавших через sms +# http://l2top.ru/edit...stVotes&uid=Ваш ID_sms&key=ключ +L2TopSmsAddress = \ No newline at end of file Index: java/com/l2jserver/gameserver/instancemanager/vote/L2TopManager.java =================================================================== --- java/com/l2jserver/gameserver/instancemanager/vote/L2TopManager.java (revision 0) +++ java/com/l2jserver/gameserver/instancemanager/vote/L2TopManager.java (revision 0) @@ -0,0 +1,325 @@ +/* + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see <http://www.gnu.org/licenses/>. + */ +package com.l2jserver.gameserver.instancemanager.vote; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Socket; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Calendar; +import java.util.Collection; +import java.util.NoSuchElementException; +import java.util.StringTokenizer; +import java.util.logging.Logger; +import com.l2jserver.Config; +import com.l2jserver.L2DatabaseFactory; +import com.l2jserver.gameserver.ThreadPoolManager; +import com.l2jserver.gameserver.model.L2World; +import com.l2jserver.gameserver.model.actor.instance.L2PcInstance; + +public class L2TopManager +{ + private static Logger _log = Logger.getLogger(L2TopManager.class.getName()); + + private static final String voteWeb = Config.DATAPACK_ROOT + "/data/vote-web.txt"; + private static final String voteSms = Config.DATAPACK_ROOT + "/data/vote-sms.txt"; + private static L2TopManager _instance; + + public static L2TopManager getInstance() + { + if (_instance == null) + { + _instance = new L2TopManager(); + } + return _instance; + } + + public L2TopManager() + { + if (Config.L2TOP_SERVICE_ENABLED) + { + ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new ConnectAndUpdate(), Config.L2TOP_INTERVAL * 60000, Config.L2TOP_INTERVAL * 60000); + ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new Clean(), Config.L2TOP_INTERVAL * 60000, Config.L2TOP_INTERVAL * 60000); + ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new GiveReward(), Config.L2TOP_INTERVAL * 60000, Config.L2TOP_INTERVAL * 60000); + _log.info("L2TopManager: Started."); + } + else + { + _log.info("L2TopManager: Disabled."); + } + } + + private void update() + { + String out_sms = getPage(Config.L2TOP_SMS_ADRESS); + String out_web = getPage(Config.L2TOP_WEB_ADRESS); + + File sms = new File(voteSms); + File web = new File(voteWeb); + FileWriter save = null; + try + { + save = new FileWriter(sms); + save.write(out_sms); + save = new FileWriter(web); + save.write(out_web); + } + catch (IOException e) + { + e.printStackTrace(); + } + finally + { + try + { + if (save != null) + save.close(); + } + catch (Exception e1) + { + e1.printStackTrace(); + } + } + } + + private static String getPage(String address) + { + StringBuffer buf = new StringBuffer(); + try + { + Socket s = new Socket("l2top.ru", 80); + s.setSoTimeout(30000); + String request = "GET " + address + " HTTP/1.1\r\n" + "User-Agent: http:\\" + Config.L2_TOP_SERVER_ADRES + " server\r\n" + "Host: http:\\" + Config.L2_TOP_SERVER_ADRES + " \r\n" + "Accept: */*\r\n" + "Connection: close\r\n" + "\r\n"; + + s.getOutputStream().write(request.getBytes()); + BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "Cp1251")); + + for (String line = in.readLine(); line != null; line = in.readLine()) + { + buf.append(line); + buf.append("\r\n"); + } + s.close(); + } + catch (Exception e) + { + buf.append("Connection error"); + } + return buf.toString(); + } + + private void parse(boolean sms) + { + try + { + BufferedReader in = new BufferedReader(new FileReader(sms ? voteSms : voteWeb)); + String line = in.readLine(); + while (line != null) + { + Calendar cal = Calendar.getInstance(); + int year = cal.get(1); + if (line.startsWith("" + year)) + { + try + { + StringTokenizer st = new StringTokenizer(line, "\t -:"); + cal.set(1, Integer.parseInt(st.nextToken())); + cal.set(2, Integer.parseInt(st.nextToken())); + cal.set(5, Integer.parseInt(st.nextToken())); + cal.set(11, Integer.parseInt(st.nextToken())); + cal.set(12, Integer.parseInt(st.nextToken())); + cal.set(13, Integer.parseInt(st.nextToken())); + cal.set(14, 0); + String nick = st.nextToken(); + int mult = 1; + if (sms) + mult = Integer.parseInt(new StringBuffer(st.nextToken()).delete(0, 1).toString()); + if (cal.getTimeInMillis() + Config.L2TOP_CLEAN_DAY * 86400000 > System.currentTimeMillis()) + checkAndSaveFromDb(cal.getTimeInMillis(), nick, mult); + } + catch (NoSuchElementException nsee) + { + } + } + else + line = in.readLine(); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + private synchronized void clean() + { + Calendar cal = Calendar.getInstance(); + cal.add(6, -Config.L2TOP_CLEAN_DAY); + Connection con = null; + PreparedStatement statement = null; + try + { + con = L2DatabaseFactory.getInstance().getConnection(); + statement = con.prepareStatement("DELETE FROM character_vote WHERE date<?"); + statement.setLong(1, cal.getTimeInMillis()); + statement.execute(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + finally + { + L2DatabaseFactory.close(con); + } + } + + private synchronized void checkAndSaveFromDb(long date, String nick, int mult) + { + Connection con = null; + PreparedStatement statement = null; + ResultSet rset = null; + try + { + con = L2DatabaseFactory.getInstance().getConnection(); + statement = con.prepareStatement("SELECT obj_Id FROM characters WHERE char_name=?"); + statement.setString(1, nick); + rset = statement.executeQuery(); + int objId = 0; + if (rset.next()) + { + objId = rset.getInt("obj_Id"); + } + if (objId > 0) + { + L2DatabaseFactory.close(con); + statement = con.prepareStatement("SELECT * FROM character_vote WHERE id=? AND date=? AND multipler=?"); + statement.setInt(1, objId); + statement.setLong(2, date); + statement.setInt(3, mult); + rset = statement.executeQuery(); + if (!rset.next()) + { + L2DatabaseFactory.close(con); + statement = con.prepareStatement("INSERT INTO character_vote (date, id, nick, multipler) values (?,?,?,?)"); + statement.setLong(1, date); + statement.setInt(2, objId); + statement.setString(3, nick); + statement.setInt(4, mult); + statement.execute(); + } + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + finally + { + L2DatabaseFactory.close(con); + } + } + + private synchronized void giveReward() + { + Connection con = null; + PreparedStatement statement = null; + ResultSet rset = null; + try + { + con = L2DatabaseFactory.getInstance().getConnection(); + final Collection<L2PcInstance> players = L2World.getInstance().getAllPlayers().values(); + for (L2PcInstance player : players) + { + int objId = player.getObjectId(); + int mult = 0; + statement = con.prepareStatement("SELECT multipler FROM character_vote WHERE id=? AND has_reward=0"); + statement.setInt(1, objId); + rset = statement.executeQuery(); + while (rset.next()) + { + mult += rset.getInt("multipler"); + } + + L2DatabaseFactory.close(con); + statement = con.prepareStatement("UPDATE character_vote SET has_reward=1 WHERE id=?"); + statement.setInt(1, objId); + statement.executeUpdate(); + if (mult > 0) + { + player.sendMessage("Администрация сервера " + Config.L2_TOP_SERVER_ADRES + " благодарит вас за голосование"); + player.getInventory().addItem("L2Top Reward", Config.L2_TOP_REWARD_ID, Config.L2_TOP_REWARD_COUNT * mult, player, null); + } + L2DatabaseFactory.close(con); + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + finally + { + L2DatabaseFactory.close(con); + } + } + + private class GiveReward + implements Runnable + { + private GiveReward() + { + } + + public void run() + { + L2TopManager.this.giveReward(); + } + } + + private class Clean + implements Runnable + { + private Clean() + { + } + + public void run() + { + L2TopManager.this.clean(); + } + } + + private class ConnectAndUpdate + implements Runnable + { + private ConnectAndUpdate() + { + } + + public void run() + { + L2TopManager.this.update(); + L2TopManager.this.parse(true); + L2TopManager.this.parse(false); + } + } +} \ No newline at end of file Дата пак ### Eclipse Workspace Patch 1.0 #P L2jEnergy_DataPack Index: tools/full_install.sql =================================================================== --- tools/full_install.sql (revision 3) +++ tools/full_install.sql (working copy) @@ -57,6 +57,7 @@ DROP TABLE IF EXISTS character_tpbookmark; DROP TABLE IF EXISTS character_ui_actions; DROP TABLE IF EXISTS character_ui_categories; +DROP TABLE IF EXISTS character_vote; DROP TABLE IF EXISTS characters; DROP TABLE IF EXISTS clan_data; DROP TABLE IF EXISTS clan_notices; Index: sql/character_vote.sql =================================================================== --- sql/character_vote.sql (revision 0) +++ sql/character_vote.sql (revision 0) @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS `character_vote` ( + `date` bigint(14) NOT NULL default '0', + `id` int(10) NOT NULL default '0', + `nick` varchar(255) NOT NULL default '''''', + `multipler` int(9) NOT NULL default '0', + `has_reward` int(1) NOT NULL default '0', + PRIMARY KEY (`date`,`id`,`nick`,`multipler`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; \ No newline at end of file Index: tools/database_installer.bat =================================================================== --- tools/database_installer.bat (revision 3) +++ tools/database_installer.bat (working copy) @@ -755,6 +755,7 @@ character_tpbookmark.sql character_ui_actions.sql character_ui_categories.sql +character_vote.sql characters.sql clan_data.sql clan_notices.sql Index: tools/database_installer.sh =================================================================== --- tools/database_installer.sh (revision 3) +++ tools/database_installer.sh (working copy) @@ -398,6 +398,7 @@ $MYG < ../sql/character_tpbookmark.sql &> /dev/null $MYG < ../sql/character_ui_actions.sql &> /dev/null $MYG < ../sql/character_ui_categories.sql &> /dev/null +$MYG < ../sql/character_vote.sql &> /dev/null $MYG < ../sql/characters.sql &> /dev/null $MYG < ../sql/clan_data.sql &> /dev/null $MYG < ../sql/clan_notices.sql &> /dev/null Этот код был переделан из сборки maddev (Phoenix Epilogue) Он также станет под следующие сборки: L2DC, L2VT, L2Open, и т.п (нужно только сменить импорты). Для установки нужен исходный код)) Спасибо всем за внимание))) Вот ссылка на diff файлы)) P.S. Копипастерам указывать имя автора, автором являюсь я, Мо3олЬ))) 2 Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты
РукьЖопь 0 Опубликовано 18 марта, 2013 Как я понимаю нужен L2TopManager.java откуда он у Вас на l2jserver ? Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты
РукьЖопь 0 Опубликовано 18 марта, 2013 (изменено) разобрался всё ок извините Изменено 18 марта, 2013 пользователем РукьЖопь Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты
RoyalGost 277 Опубликовано 8 мая, 2013 Автоматическое сообщение Эта тема была перемещена из "Дополнения" в "Web составляющие". Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты