Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- diff --git a/aCis_gameserver/java/net/sf/l2j/Config.java b/aCis_gameserver/java/net/sf/l2j/Config.java
- index 49c4168..1083190 100644
- --- a/aCis_gameserver/java/net/sf/l2j/Config.java
- +++ b/aCis_gameserver/java/net/sf/l2j/Config.java
- @@ -797,6 +797,27 @@
- public static String[] CTF_TIMES_LIST;
- public static String[] DM_TIMES_LIST;
- + /** PVP EVENT*/
- + public static String NAME_PVP;
- +
- + public static boolean PVP_EVENT_ENABLED;
- + public static String[] PVP_EVENT_INTERVAL;
- + public static int PVP_EVENT_RUNNING_TIME;
- + public static int[][] PVP_EVENT_REWARDS;
- + public static boolean ALLOW_SPECIAL_PVP_REWARD;
- + public static List<int[]> PVP_SPECIAL_ITEMS_REWARD;
- + public static boolean SCREN_MSG_PVP;
- + public static int pvp_locx;
- + public static int pvp_locy;
- + public static int pvp_locz;
- +
- + public static int PC_1x1;
- + public static int PC_PVP;
- + public static int MISSION_PVP_REWARD_ID;
- + public static int MISSION_PVP_REWARD_AMOUNT;
- + public static int MISSION_PVP_CONT;
- + public static boolean ACTIVE_MISSION_PVP;
- +
- /** Deathmatch event settings */
- public static boolean ALLOW_DM_EVENT;
- public static int DM_MIN_PLAYERS;
- diff --git a/aCis_gameserver/java/net/sf/l2j/commons/HttpClientApi.java b/aCis_gameserver/java/net/sf/l2j/commons/HttpClientApi.java
- new file mode 100644
- index 0000000..d8e3d73
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/commons/HttpClientApi.java
- @@ -0,0 +1,116 @@
- +package net.sf.l2j.commons;
- +
- +import java.net.URI;
- +import java.net.http.HttpClient;
- +import java.net.http.HttpRequest;
- +import java.net.http.HttpRequest.Builder;
- +import java.net.http.HttpResponse;
- +import java.time.Duration;
- +import java.util.Map;
- +import java.util.concurrent.CompletableFuture;
- +
- +import java.util.logging.Logger;
- +
- +public class HttpClientApi
- +{
- +protected static final Logger LOGGER = null;
- +private static final HttpClient HTTPCLIENT = HttpClient.newBuilder()
- + .connectTimeout(Duration.ofSeconds(10)) // tempo para conectar-se
- + .version(HttpClient.Version.HTTP_2)
- + .build();
- +
- +public CompletableFuture<String> sendGetAsync(String url)
- +{
- + final HttpRequest request = HttpRequest.newBuilder()
- + .uri(URI.create(url))
- + .timeout(Duration.ofSeconds(10)) // tempo para resposta
- + .GET()
- + .build();
- +
- + return HTTPCLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
- + .thenApply(HttpResponse::body)
- + .exceptionally(e ->
- + {
- + LOGGER. warning("Erro na requisição GET async. "+e);
- + return null;
- + });
- +}
- +
- +public CompletableFuture<HttpResponse<String>> sendPostAsync(String url, String jsonBody)
- +{
- + return sendPostAsync(url, jsonBody, null);
- +}
- +
- +public CompletableFuture<HttpResponse<String>> sendPostAsync(String url, String jsonBody, Map<String, String> headers)
- +{
- + final Builder requestBuilder = HttpRequest.newBuilder()
- + .uri(URI.create(url))
- + .timeout(Duration.ofSeconds(10))
- + .header("Content-Type", "application/json")
- + .POST(HttpRequest.BodyPublishers.ofString(jsonBody));
- +
- + // Cabeçalhos adicionais
- + if (headers != null)
- + headers.forEach(requestBuilder::header);
- +
- + final HttpRequest request = requestBuilder.build();
- +
- + return HTTPCLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
- + .exceptionally(e ->
- + {
- + LOGGER. warning("Erro na requisição POST async. "+e);
- + return null;
- + });
- +}
- +
- +public String sendGet(String url)
- +{
- + final HttpRequest request = HttpRequest.newBuilder()
- + .uri(URI.create(url))
- + .timeout(Duration.ofSeconds(10))
- + .GET()
- + .build();
- +
- + try
- + {
- + final HttpResponse<String> response = HTTPCLIENT.send(request, HttpResponse.BodyHandlers.ofString());
- + return response.body();
- + }
- + catch (Exception e)
- + {
- + LOGGER. warning("Erro na requisição GET. "+e);
- + return null;
- + }
- +}
- +
- +public String sendPost(String url, String json)
- +{
- + final HttpRequest request = HttpRequest.newBuilder()
- + .uri(URI.create(url))
- + .timeout(Duration.ofSeconds(10))
- + .header("Content-Type", "application/json")
- + .POST(HttpRequest.BodyPublishers.ofString(json))
- + .build();
- +
- + try
- + {
- + final HttpResponse<String> response = HTTPCLIENT.send(request, HttpResponse.BodyHandlers.ofString());
- + return response.body();
- + }
- + catch (Exception e)
- + {
- + LOGGER. warning("Erro na requisição POST. "+e);
- + return null;
- + }
- +}
- +
- +public static HttpClientApi getInstance()
- +{
- + return SingletonHolder.INSTANCE;
- +}
- +
- +private static class SingletonHolder
- +{
- + protected static final HttpClientApi INSTANCE = new HttpClientApi();
- +}
- +}
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/commons/data/Pagination.java b/aCis_gameserver/java/net/sf/l2j/commons/data/Pagination.java
- new file mode 100644
- index 0000000..0029598
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/commons/data/Pagination.java
- @@ -0,0 +1,155 @@
- +package net.sf.l2j.commons.data;
- +
- +import java.util.AbstractList;
- +import java.util.Collections;
- +import java.util.Comparator;
- +import java.util.List;
- +import java.util.function.Predicate;
- +import java.util.stream.IntStream;
- +import java.util.stream.Stream;
- +
- +import net.sf.l2j.commons.lang.StringUtil;
- +
- +public class Pagination<A> extends AbstractList<A>
- +{
- + private static final String NORMAL_LINE_SIZE = "<img height=17>";
- +
- + private final StringBuilder _content = new StringBuilder();
- +
- + private List<A> _list;
- + private int _page;
- + private int _limit;
- + private int _total;
- + private int _totalEntries;
- +
- + public Pagination(Stream<A> stream, int page, int limit)
- + {
- + this(stream, page, limit, null, null);
- + }
- +
- + public Pagination(Stream<A> stream, int page, int limit, Predicate<A> filter)
- + {
- + this(stream, page, limit, filter, null);
- + }
- +
- + public Pagination(Stream<A> stream, int page, int limit, Comparator<A> comparator)
- + {
- + this(stream, page, limit, null, comparator);
- + }
- +
- + public Pagination(Stream<A> stream, int page, int limit, Predicate<A> filter, Comparator<A> comparator)
- + {
- + _list = initList(stream, filter, comparator);
- + _totalEntries = _list.size();
- + _limit = Math.max(limit, 1);
- + _total = _list.size() / _limit + (_list.size() % _limit == 0 ? 0 : 1);
- + _page = Math.min(Math.max(page, 1), Math.max(1, _total));
- +
- +
- + if (_list.isEmpty())
- + return;
- +
- + _list = _list.subList((Math.min(page, _total) - 1) * limit, Math.min(Math.min(page, _total) * limit, _list.size()));
- + }
- +
- + private List<A> initList(Stream<A> stream, Predicate<A> filter, Comparator<A> comparator)
- + {
- + if (stream == null)
- + return Collections.emptyList();
- +
- + if (filter == null && comparator == null)
- + return stream.toList();
- +
- + if (comparator == null)
- + return stream.filter(filter).toList();
- +
- + if (filter == null)
- + return stream.sorted(comparator).toList();
- +
- + return stream.filter(filter).sorted(comparator).toList();
- + }
- +
- + public void append(Object... content)
- + {
- + StringUtil.append(_content, content);
- + }
- +
- + public void generateSpace()
- + {
- + IntStream.range(size(), _limit).forEach(x -> append(NORMAL_LINE_SIZE));
- + }
- +
- + public void generateSpace(int height)
- + {
- + IntStream.range(size(), _limit).forEach(x -> append("<img height=", height, ">"));
- + }
- +
- + public void generatePages(String action)
- + {
- + append(buildPages(action));
- + }
- +
- + public void generateSearch(String action, int height)
- + {
- + append("<table width=280 height=", height, "><tr>");
- + append("<td width=70 align=center>Search</td>");
- + append("<td width=140><edit var=\"search\" width=130 height=15></td>");
- + append("<td width=70><button value=\"Find\" action=\"", action, " 1 $search\" width=65 height=19 back=\"L2UI_ch3.smallbutton2_over\" fore=\"L2UI_ch3.smallbutton2\"></td>");
- + append("</tr><tr>");
- + append("<td></td>");
- + append("<td align=center>Found ", _totalEntries, " results</td>");
- + append("<td></td>");
- + append("</tr></table>");
- + }
- +
- + public String getContent()
- + {
- + return _content.toString();
- + }
- +
- + public void resetContent()
- + {
- + _content.setLength(0);
- + }
- +
- + @Override
- + public A get(int index)
- + {
- + return _list.get(index);
- + }
- +
- + @Override
- + public int size()
- + {
- + return _list.size();
- + }
- +
- + public String getPages(String action)
- + {
- + return buildPages(action);
- + }
- +
- + private String buildPages(String action)
- + {
- + final StringBuilder sb = new StringBuilder();
- + sb.append("<table width=280 bgcolor=000000><tr><td FIXWIDTH=22 align=center><img height=2><button action=\"" + action.replace("%page%", String.valueOf(1)) + "\" back=L2UI_CH3.prev1_down fore=L2UI_CH3.prev1 width=16 height=16></td>");
- +
- + for (int index = _page - 5; index < _page - 1; index++)
- + sb.append("<td FIXWIDTH=26 align=center>" + (index < 0 ? "" : "<a action=\"" + action.replace("%page%", String.valueOf(index + 1)) + "\">" + String.format("%02d", (index + 1)) + "</a>") + "</td>");
- +
- + sb.append("<td FIXWIDTH=26 align=center><font color=LEVEL>" + String.format("%02d", Math.max(_page, 1)) + "</font></td>");
- +
- + for (int index = _page; index < _page + 4; index++)
- + sb.append("<td FIXWIDTH=26 align=center>" + (index < _total ? "<a action=\"" + action.replace("%page%", String.valueOf(index + 1)) + "\">" + String.format("%02d", (index + 1)) + "</a>" : "") + "</td>");
- +
- + sb.append("<td FIXWIDTH=22 align=center><img height=2><button action=\"" + action.replace("%page%", String.valueOf(_total)) + "\" back=L2UI_CH3.next1_down fore=L2UI_CH3.next1 width=16 height=16></td></tr></table>");
- + sb.append("<img src=\"L2UI.SquareGray\" width=280 height=1>");
- +
- + return sb.toString();
- + }
- +
- + public int getTotalEntries()
- + {
- + return _totalEntries;
- + }
- +}
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/AblyWebhook.java b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/AblyWebhook.java
- new file mode 100644
- index 0000000..602f120
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/AblyWebhook.java
- @@ -0,0 +1,83 @@
- +package net.sf.l2j.commons.messagebroker;
- +
- +import java.util.List;
- +import java.util.logging.Logger;
- +
- +import net.sf.l2j.loginserver.LoginController;
- +import net.sf.l2j.loginserver.model.AccountInfo;
- +
- +public class AblyWebhook
- +{
- + protected static final Logger LOGGER = Logger.getLogger(AblyWebhook.class.getName());
- +public static class Envelope
- +{
- + public String channel;
- + private List<Message> messages;
- +
- +
- + /**
- + * @return Nome do canal sem a identificação do namespace do Ably
- + */
- + public String getChannel()
- + {
- + return channel.replace("GS:", "").replace("LS:", "");
- + }
- +
- + /*
- + * Somente uma mensagem é trocada por vez
- + */
- + public String getMessage()
- + {
- + return messages.get(0).data;
- + }
- +}
- +
- +public static class Message
- +{
- + public String data;
- +}
- +
- +public static class CustomerData
- +{
- + public String code; // esse campo é enviado quando existe um problema de autenticação
- + private int id = -1; // id do usuário em customer.* e id da compra em order.*
- + private int customer_id = -1; // id do comprador em order.*
- + public String role;
- + private String username;
- + public String password_hash;
- + public String webhook_secrect;
- +
- + /*
- + * Em compras, o WooCommerce não envia o username, apenas o customer_id.
- + * Ao deletar um cliente, o WooCommerce está enviando somente o id do usuário
- + */
- + public String getUsername()
- + {
- + if (username == null)
- + username = LoginController.getInstance().getAccountLogin(getUserId());
- +
- + return username;
- + }
- +
- + public int getUserId()
- + {
- + return customer_id < 0 ? id : customer_id;
- + }
- +}
- +
- +public static class OrderData
- +{
- + public int id;
- + public int number;
- + public String status;
- + public List<ProductData> line_items;
- +}
- +
- +public static class ProductData
- +{
- + public String name;
- + public double price;
- + public int product_id;
- + public int quantity;
- +}
- +}
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MBVariables.java b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MBVariables.java
- new file mode 100644
- index 0000000..c26e8fe
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MBVariables.java
- @@ -0,0 +1,53 @@
- +package net.sf.l2j.commons.messagebroker;
- +
- +import java.util.HashMap;
- +import java.util.Map;
- +
- +public class MBVariables
- +{
- +// Ativar ou desativar. É necessário reinicar para alterar.
- +public static final boolean ENABLED = true;
- +
- +// Wordpress e WooCommerce
- +public static final String WP_SITE_URL = "http://l2jbrasil.com";
- +public static final String WC_CONSUMER_KEY = "ck_123213213213213213123123454354354354319b9a5";
- +public static final String WC_CONSUMER_SECRET = "ck_123213213213213213123123454354354354319b9a5";
- +
- +// Chave de API do Ably
- +public static final String ABLY_API_KEY = "shClSA.nNbwiA:gu_1Uf1232131231231234Sgn2LY";
- +
- +// Definir accessLevel 8 aos usuários que também são administradores no wordpress
- +// Isso permite criar ou definir admins no l2 a partir do painel
- +// public static final boolean CREATE_ADMIN = false;
- +
- +// Desconectar conta (se estiver online) ao alterar seus dados
- +public static final boolean LOGOUT_ACCOUNT_CHANGE = true;
- +
- +// Gameserver
- +public static final String LS_SERVER_ENDPOINT = "us-east-1-a-queue.ably.io:5671";
- +public static final String LS_QUEUE_NAME = "sh123A:loginserver";
- +public static final String LS_VHOST = "shared";
- +
- +// Loginserver
- +public static final String GS_SERVER_ENDPOINT = "us-east-1-a-queue.ably.io:5671";
- +public static final String GS_QUEUE_NAME = "shC123a:ameserver";
- +public static final String GS_VHOST = "shared";
- +
- +// Não mexa
- +public static final Map<Integer, Integer> PRODUCTS = new HashMap<>();
- +public static final Map<String, String> SECRETS = new HashMap<>();
- +
- +static
- +{
- + // Ao comprar um produto site, qual item o player deve receber?
- + // Para criar essa relação, insira o ID do produto do WooCommerce depois da vírgula o ID do item do L2
- + // Repita quantas vezes for necessário, mas uma relação por linha
- + PRODUCTS.put(354, 9527);
- + //PRODUCTS.put(1000, 3470);
- +
- + // Insira aqui os valores dos campos 'Segredo' de cada webhook do WooCommerce
- + SECRETS.put("LS:customer.created", "123122222222222VA:sICZ@$p_dqf!l");
- + SECRETS.put("LS:customer.updated", "I!t#{4#1222222222222222222");
- + SECRETS.put("GS:order.updated", "~Hf7uQec}ii12122222222222w#@s}wZn:x,8J");
- +}
- +}
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MessageBrokerHandler.java b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MessageBrokerHandler.java
- new file mode 100644
- index 0000000..c172b36
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MessageBrokerHandler.java
- @@ -0,0 +1,151 @@
- +package net.sf.l2j.commons.messagebroker;
- +
- +import com.google.gson.Gson;
- +import com.rabbitmq.client.Channel;
- +import com.rabbitmq.client.Connection;
- +import com.rabbitmq.client.ConnectionFactory;
- +import com.rabbitmq.client.DeliverCallback;
- +
- +import java.util.logging.Logger;
- +
- +import net.sf.l2j.commons.messagebroker.AblyWebhook.CustomerData;
- +import net.sf.l2j.commons.messagebroker.AblyWebhook.Envelope;
- +
- +import net.sf.l2j.loginserver.model.AccountInfo;
- +import net.sf.l2j.loginserver.LoginController;
- +
- +public abstract class MessageBrokerHandler
- +{
- + protected static final Logger LOGGER = Logger.getLogger(MessageBrokerHandler.class.getName());
- +
- + protected static final Gson GSON = new Gson();
- +
- + private String _serverEndpoint;
- + private String _queueName;
- + private String _vHost;
- +
- + private Connection _connection;
- + private Channel _channel;
- +
- + protected MessageBrokerHandler(String serverEndpoint, String queueName, String vHost)
- + {
- + if (!MBVariables.ENABLED)
- + return;
- +
- + _serverEndpoint = serverEndpoint;
- + _queueName = queueName;
- + _vHost = vHost;
- +
- + start();
- + }
- +
- + private void start()
- + {
- + try
- + {
- + final ConnectionFactory factory = new ConnectionFactory();
- + factory.setUri("amqps://" + MBVariables.ABLY_API_KEY + "@" + _serverEndpoint + "/" + _vHost);
- + _connection = factory.newConnection();
- + _channel = _connection.createChannel();
- +
- + final DeliverCallback deliverCallback = (consumerTag, delivery) ->
- + {
- + String message = new String(delivery.getBody(), "UTF-8");
- + basicHandle(message);
- + };
- +
- + _channel.basicConsume(_queueName, true, deliverCallback, consumerTag -> {});
- +
- + LOGGER.info("{} started. "+getClass().getSimpleName());
- + }
- + catch (Exception e)
- + {
- + LOGGER.warning("Falha ao iniciar o {"+getClass().getSimpleName()+"}. "+ e);
- + }
- + }
- +
- + public void stop()
- + {
- + try
- + {
- + if (_channel != null && _channel.isOpen())
- + _channel.close();
- +
- + if (_connection != null && _connection.isOpen())
- + _connection.close();
- + }
- + catch (Exception e)
- + {
- + e.printStackTrace();
- + }
- + }
- +
- + protected abstract void handleMessage(Envelope envelope);
- +
- + /*
- + * O loginserver e o gameserver devem ser consultados através de seus próprios métodos
- + */
- + protected abstract void checkOnlineAccount(String username);
- +
- + private void basicHandle(String message)
- + {
- + try
- + {
- + final Envelope envelope = GSON.fromJson(message, Envelope.class);
- + handleMessage(envelope);
- + }
- + catch (Exception e)
- + {
- + LOGGER.warning("Falha ao desserializar mensagem recebida no "+getClass().getSimpleName()+". "+ e);
- + }
- + }
- +
- + protected boolean validadeAuth(String channel, CustomerData customer)
- + {
- + // Isso pode acontecer quando algumas configurações de segurança do wordpress são alteradas, os webhooks ficam sem permissão e necessário recriá-los
- + if (customer.code != null)
- + {
- + LOGGER.warning("O webhook "+ channel+" não está enviando os dados corretamente. Delete o atual e crie um novo. ");
- + return false;
- + }
- +
- + if (!MBVariables.SECRETS.containsKey(channel) || !MBVariables.SECRETS.get(channel).equals(customer.webhook_secrect))
- + {
- +
- + LOGGER.warning("Falha ao verificar o segredo do canal "+channel+" do "+getClass().getSimpleName()+".");
- + return false;
- + }
- +
- + return true;
- + }
- +
- + /*
- + * O AccountInfo é o nosso custom, mas não verificamos porque ele é criado junto a conta, e está no Gameserver.
- + */
- + protected boolean validateAccount(CustomerData customer)
- + {
- + if (customer.getUsername() == null)
- + return false;
- +
- + final AccountInfo account = LoginController.getInstance().getAccount(customer.getUsername());
- +
- + if (account == null)
- + {
- + LOGGER.warning("A conta '"+customer.getUsername()+"' enviada pelo Wordpress não existe no servidor.");
- + return false;
- + }
- +
- + if (account.getWpUserId() != customer.getUserId())
- + {
- + LOGGER.warning("A conta '"+customer.getUsername()+"' enviada pelo Wordpress não é a mesma que existe no servidor.");
- + return false;
- + }
- +
- + return true;
- + }
- +
- + protected Gson getGson()
- + {
- + return GSON;
- + }
- +}
- diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java b/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java
- index 0c9fb95..4415c8c 100644
- --- a/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java
- +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java
- @@ -14,6 +14,8 @@
- import net.sf.l2j.Config;
- import net.sf.l2j.L2DatabaseFactory;
- +
- +import net.sf.l2j.commons.HttpClientApi;
- import net.sf.l2j.commons.concurrent.ThreadPool;
- import net.sf.l2j.commons.lang.StringUtil;
- import net.sf.l2j.commons.mmocore.SelectorConfig;
- @@ -122,6 +124,7 @@
- import net.sf.l2j.gameserver.taskmanager.ShadowItemTaskManager;
- import net.sf.l2j.gameserver.taskmanager.WaterTaskManager;
- import net.sf.l2j.gameserver.xmlfactory.XMLDocumentFactory;
- +import net.sf.l2j.loginserver.LoginController;
- import net.sf.l2j.util.DeadLockDetector;
- import net.sf.l2j.util.IPv4Filter;
- @@ -205,13 +208,22 @@
- /** Party Farm Event */
- StringUtil.printSection("Party Farm Event");
- _log.info("Evento Party Farm");
- - if (Config.PARTY_FARM_BY_TIME_OF_DAY && !Config.START_PARTY) {
- + /*if (Config.PARTY_FARM_BY_TIME_OF_DAY && !Config.START_PARTY) {
- InitialPartyFarm.getInstance().StartCalculationOfNextEventTime();
- _log.info("[Party Farm Time]: Enabled");
- } else if (Config.START_PARTY && !Config.PARTY_FARM_BY_TIME_OF_DAY) {
- _log.info("[Start Spawn Party Farm]: Enabled");
- ThreadPool.schedule(new SpawnMonsters(), Config.NPC_SERVER_DELAY * 1000L);
- - }
- + } */
- + if ((Config.START_PARTY))
- + {
- + _log.info("[Party Farm Time]: Enabled");
- + InitialPartyFarm.getInstance().StartCalculationOfNextEventTime();
- + }
- + else
- + {
- + _log.info("Party Farm is disabled.");
- + }
- /** Tournament 2x2 4x4 9x9*/
- StringUtil.printSection("Tournament 2x2 4x4 9x9");
- @@ -369,6 +381,12 @@
- BoatTalkingGludin.load();
- }
- + StringUtil.printSection("WORDPRESS - Message Broker");
- + LoginController.load();
- + HttpClientApi.getInstance();
- + GameMessageConsumer.getInstance();
- +
- +
- StringUtil.printSection("Events");
- DerbyTrackManager.getInstance();
- LotteryManager.getInstance();
- @@ -475,7 +493,7 @@
- return _selectorThread;
- }
- - public class SpawnMonsters implements Runnable
- + /*public class SpawnMonsters implements Runnable
- {
- public SpawnMonsters()
- {
- @@ -489,5 +507,5 @@
- PartyFarm.spawnMonsters();
- }
- - }
- + } */
- }
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/data/sql/PlayerInfoTable.java b/aCis_gameserver/java/net/sf/l2j/gameserver/data/sql/PlayerInfoTable.java
- index 4953582..7289497 100644
- --- a/aCis_gameserver/java/net/sf/l2j/gameserver/data/sql/PlayerInfoTable.java
- +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/data/sql/PlayerInfoTable.java
- @@ -3,6 +3,7 @@
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- +import java.util.List;
- import java.sql.SQLException;
- import java.util.Map;
- import java.util.Map.Entry;
- @@ -186,4 +187,9 @@
- {
- protected static final PlayerInfoTable INSTANCE = new PlayerInfoTable();
- }
- +
- + public final List<Integer> getAccountCharacters(String accountName)
- + {
- + return _infos.entrySet().stream().filter(m -> m.getValue().getAccountName().equalsIgnoreCase(accountName)).map(Entry::getKey).toList();
- + }
- }
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/model/actor/Player.java b/aCis_gameserver/java/net/sf/l2j/gameserver/model/actor/Player.java
- index 23d55bb..a06b388 100644
- --- a/aCis_gameserver/java/net/sf/l2j/gameserver/model/actor/Player.java
- +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/model/actor/Player.java
- @@ -22,6 +22,7 @@
- import java.util.concurrent.locks.ReentrantLock;
- import java.util.logging.Level;
- import java.util.stream.Collectors;
- +import java.util.List;
- import net.sf.l2j.commons.concurrent.ThreadPool;
- import net.sf.l2j.commons.math.MathUtil;
- @@ -264,6 +265,8 @@
- import net.sf.l2j.gameserver.model.actor.instance.Agathion;
- +import net.sf.l2j.gameserver.wordpress.WooOrdersManager;
- +
- /**
- * This class represents a player in the world.<br>
- * There is always a client-thread connected to this (except if a player-store is activated upon logout).
- @@ -8426,6 +8429,8 @@
- revalidateZone(true);
- notifyFriends(true);
- + // Verificar se existe alguma compra pendente para ser entregue
- + WooOrdersManager.getInstance().showWaitingOrders(this);
- }
- public long getLastAccess()
- @@ -11303,5 +11308,7 @@
- {
- return aga;
- }
- +
- +
- }
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooCommerceAPI.java b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooCommerceAPI.java
- new file mode 100644
- index 0000000..526f484
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooCommerceAPI.java
- @@ -0,0 +1,53 @@
- +package net.sf.l2j.gameserver.wordpress;
- +
- +import com.google.gson.JsonObject;
- +
- +import java.util.Base64;
- +import java.util.Map;
- +import java.util.logging.Logger;
- +
- +import net.sf.l2j.commons.HttpClientApi;
- +import net.sf.l2j.commons.messagebroker.MBVariables;
- +
- +public class WooCommerceAPI
- +{
- + private static final Logger LOGGER = Logger.getLogger(WooCommerceAPI.class.getName());
- +
- + private static String getAuthHeader()
- + {
- + final String authString = MBVariables.WC_CONSUMER_KEY + ":" + MBVariables.WC_CONSUMER_SECRET;
- + return "Basic " + Base64.getEncoder().encodeToString(authString.getBytes());
- + }
- +
- + private static String getApiUrl()
- + {
- + return MBVariables.WP_SITE_URL + "/wp-json/wc/v3/";
- + }
- +
- + public void addOrderNote(int orderId, boolean customerNote, String message)
- + {
- + final String url = getApiUrl() + "orders/" + orderId + "/notes";
- + final JsonObject json = new JsonObject();
- +
- + json.addProperty("note", message);
- + json.addProperty("customer_note", customerNote);
- +
- + HttpClientApi.getInstance()
- + .sendPostAsync(url, json.toString(), Map.of("Authorization", getAuthHeader()))
- + .thenAccept(response ->
- + {
- + if (response.statusCode() != 200 && response.statusCode() != 201)
- + LOGGER.warning("Não foi possível adicionar uma nota na Order #"+orderId+" do WooCommerce. StatusCode: "+response.statusCode());
- + });
- + }
- +
- + public static WooCommerceAPI getInstance()
- + {
- + return SingletonHolder.INSTANCE;
- + }
- +
- + private static class SingletonHolder
- + {
- + protected static final WooCommerceAPI INSTANCE = new WooCommerceAPI();
- + }
- +}
- diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooOrdersManager.java b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooOrdersManager.java
- new file mode 100644
- index 0000000..825d1af
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooOrdersManager.java
- @@ -0,0 +1,395 @@
- +package net.sf.l2j.gameserver.wordpress;
- +
- +import java.sql.Connection;
- +import java.sql.PreparedStatement;
- +import java.sql.ResultSet;
- +import java.util.ArrayList;
- +import java.util.Comparator;
- +import java.util.List;
- +import java.util.Map;
- +import java.util.StringTokenizer;
- +import java.util.concurrent.ConcurrentHashMap;
- +import java.util.logging.Logger;
- +
- +import net.sf.l2j.commons.data.Pagination;
- +import net.sf.l2j.commons.messagebroker.MBVariables;
- +import net.sf.l2j.commons.messagebroker.MessageBrokerHandler;
- +import net.sf.l2j.commons.messagebroker.AblyWebhook.CustomerData;
- +import net.sf.l2j.commons.messagebroker.AblyWebhook.OrderData;
- +import net.sf.l2j.commons.messagebroker.AblyWebhook.ProductData;
- +
- +import net.sf.l2j.Config;
- +import net.sf.l2j.L2DatabaseFactory;
- +import net.sf.l2j.gameserver.data.ItemTable;
- +import net.sf.l2j.gameserver.data.sql.PlayerInfoTable;
- +import net.sf.l2j.gameserver.data.ItemTable;
- +import net.sf.l2j.gameserver.model.World;
- +import net.sf.l2j.gameserver.model.actor.Player;
- +import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
- +import net.sf.l2j.loginserver.model.AccountInfo;
- +
- +public class WooOrdersManager
- +{
- + private static final Logger LOGGER = Logger.getLogger(WooOrdersManager.class.getName());
- +
- + private static final String HTML_PATH = "data/html/mods/MessageBroker/";
- +
- + private static final String LOAD_ORDERS = "SELECT * from mb_woo_orders";
- + private static final String INSERT_ORDER = "INSERT INTO mb_woo_orders (`order_id`,`item_id`,`item_count`,`account`) VALUES (?,?,?,?)";
- + private static final String DELETE_ORDER = "DELETE FROM mb_woo_orders WHERE order_id=? AND account=?";
- + private static final String DELETE_PRODUCT = "DELETE FROM mb_woo_orders WHERE order_id=? AND item_id=? AND account=?";
- + private static final String CLEAR_ACCOUNT = "DELETE FROM mb_woo_orders WHERE account=?";
- +
- + private final Map<String, List<WooOrder>> _orders = new ConcurrentHashMap<>();
- +
- + public WooOrdersManager()
- + {
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(LOAD_ORDERS);
- +
- + try (ResultSet rs = ps.executeQuery())
- + {
- + while (rs.next())
- + {
- + final String account = rs.getString("account");
- + final int orderId = rs.getInt("order_id");
- + WooOrder order = getOrder(account, orderId);
- +
- + if (order == null)
- + {
- + order = new WooOrder(orderId);
- + getAccountOrders(account).add(order);
- + }
- +
- + order.getProducts().add(new OrderProduct(orderId, rs.getInt("item_id"), rs.getInt("item_count"), account));
- + }
- + }
- + if (!_orders.isEmpty())
- + LOGGER.info(_orders.values().size() + " compras estão prontas aguardando o recebimento pelos players.");
- + }
- + catch (Exception e)
- + {
- + LOGGER.severe("Não foi possível restaurar as compras do WooCommerce. "+e);
- + }
- +
- +
- + }
- +
- + public List<WooOrder> getAccountOrders(String account)
- + {
- + return _orders.computeIfAbsent(account, k -> new ArrayList<>());
- + }
- +
- + private WooOrder getOrder(String account, int orderId)
- + {
- + return getOrder(account, orderId, false);
- + }
- +
- + private WooOrder getOrder(String account, int orderId, boolean create)
- + {
- + return getAccountOrders(account).stream().filter(o -> o.getId() == orderId).findFirst().orElse(create ? new WooOrder(orderId) : null);
- + }
- +
- + private OrderProduct getOrderProduct(String account, int orderId, int itemId)
- + {
- + return getOrder(account, orderId).getProducts().stream().filter(p -> p.getItemId() == itemId).findFirst().orElse(null);
- + }
- +
- + private boolean insertOrder(String account, int orderId, List<OrderProduct> products)
- + {
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(INSERT_ORDER);
- + for (OrderProduct product : products)
- + {
- + ps.setInt(1, product.getOrderId());
- + ps.setInt(2, product.getItemId());
- + ps.setInt(3, product.getItemCount());
- + ps.setString(4, product.getAccount());
- + ps.addBatch();
- + }
- + ps.executeBatch();
- +
- + getAccountOrders(account).add(new WooOrder(orderId, products));
- + }
- + catch (Exception e)
- + {
- + LOGGER.severe("Não foi possível inserir no banco de dados a Order #{"+orderId+"} da conta '{"+account+"}' do WooCommerce."+ e);
- + return false;
- + }
- +
- + return true;
- + }
- +
- + private boolean deleteOrder(String account, int orderId)
- + {
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(DELETE_ORDER);
- + {
- + ps.setInt(1, orderId);
- + ps.setString(2, account);
- + ps.execute();
- +
- + getAccountOrders(account).removeIf(o -> o.getId() == orderId);
- + }
- +
- + }
- + catch (Exception e)
- + {
- + LOGGER.severe("Não foi possível deletar do banco de dados a Order #"+orderId+" do WooCommerce. "+ e );
- + return false;
- + }
- +
- + return true;
- + }
- +
- + private boolean deleteProduct(String account, OrderProduct product)
- + {
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(DELETE_PRODUCT);
- + ps.setInt(1, product.getOrderId());
- + ps.setInt(2, product.getItemId());
- + ps.setString(3, account);
- + ps.execute();
- +
- + final WooOrder order = getOrder(account, product.getOrderId());
- + order.getProducts().remove(product);
- +
- + if (order.getProducts().isEmpty())
- + getAccountOrders(account).remove(order);
- + }
- + catch (Exception e)
- + {
- + LOGGER.severe("Não foi possível deletar do banco de dados o item #"+product.getItemId()+" da Order #"+product.getOrderId()+" do WooCommerce. "+ e );
- + return false;
- + }
- + return true;
- + }
- +
- + /**
- + * Apaga todas as compras pendentes da conta especificada. Utilizado na exclusão de contas.
- + * Importante para evitar que uma compras não recebidas de uma conta deletada sejam entregues a outra criada com o mesmo login.
- + * @param account : login da conta
- + */
- + public void clearAccount(String account)
- + {
- + getAccountOrders(account).clear();
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(CLEAR_ACCOUNT);
- + ps.setString(1, account);
- + ps.execute();
- +
- + }
- + catch (Exception e)
- + {
- + LOGGER.severe("Não foi possível limpar as compras do WooCommerce da conta {"+account+"}. "+ e );
- + }
- +
- + }
- +
- + public void onCompletedOrder(CustomerData customer, OrderData order)
- + {
- + if (order.line_items == null || order.line_items.isEmpty())
- + return;
- +
- + final List<OrderProduct> orderProducts = new ArrayList<>();
- + for (ProductData product : order.line_items)
- + {
- + if (!MBVariables.PRODUCTS.containsKey(product.product_id))
- + {
- + LOGGER.warning("A compra #"+order.id+" não será salva porque contém um produto do WooCommerce sem associação a um item do GameServer." );
- + return;
- + }
- +
- + final int itemId = MBVariables.PRODUCTS.get(product.product_id);
- + orderProducts.add(new OrderProduct(order.id, itemId, product.quantity, customer.getUsername()));
- + }
- +
- + if (insertOrder(customer.getUsername(), order.id, orderProducts))
- + {
- + // Notificar se algum player estiver online para receber
- + for (int playerId : PlayerInfoTable.getInstance().getAccountCharacters(customer.getUsername()))
- + {
- + final Player player = World.getInstance().getPlayer(playerId);
- + if (player != null && player.isOnline())
- + {
- + showWaitingOrders(player);
- + break;
- + }
- + }
- +
- + // Adicionar notificação para o usuário e o painel WordPress
- + WooCommerceAPI.getInstance().addOrderNote(order.id, true, "Compra concluído com sucesso. Os itens já estão disponvéis na sua conta.");
- +
- + if (Config.DEVELOPER)
- + LOGGER.warning("A Order #{"+order.id+"} realizada no WooCommerce foi recebida com sucesso.");
- + }
- + }
- +
- + /*
- + * SE a compra foi reembolsada (cancelada), então verificamos se os itens já foram entregues.
- + * Caso o player já tenha feito o resgate, não podemos fazer nada, mas se não, ainda é possível evitar que ele os obtenha.
- + */
- + public void onCancelledOrder(CustomerData customer, OrderData order)
- + {
- + // Não recebemos essa compra ou ela já foi resgatada pelo player.
- + final WooOrder wooOrder = getOrder(customer.getUsername(), order.id);
- + if (wooOrder == null)
- + return;
- +
- + if (deleteOrder(customer.getUsername(), order.id))
- + {
- + WooCommerceAPI.getInstance().addOrderNote(order.id, true, "A compra foi cancelada. Os itens não estão mais disponíveis.");
- +
- + if (Config.DEVELOPER)
- + LOGGER.warning("A solicitação de cancelamento da Order #{"+ order.id+"} realizada no WooCommerce foi recebida com sucesso.");
- + }
- + }
- +
- + public void deliverOrderProduct(Player player, int orderId, int itemId, int page)
- + {
- + final OrderProduct product = getOrderProduct(player.getAccountName(), orderId, itemId);
- + if (product == null)
- + return;
- +
- + if (deleteProduct(player.getAccountName(), product))
- + player.addItem("Item add.",product.getItemId(), product.getItemCount(),null, true);
- +
- + showOrdersWindow(player, page);
- + }
- +
- + public void handleBypass(Player player, String bypass)
- + {
- + try
- + {
- + if (!player.validateBypass(bypass))
- + return;
- +
- + final StringTokenizer st = new StringTokenizer(bypass.substring(3)); // mb_
- + final String action = st.nextToken();
- +
- + if (action.equals("list"))
- + showOrdersWindow(player, Integer.valueOf(st.nextToken()));
- + else if (action.equals("order"))
- + deliverOrderProduct(player, Integer.valueOf(st.nextToken()), Integer.valueOf(st.nextToken()), Integer.valueOf(st.nextToken()));
- + else
- + LOGGER.warning("Bypass '{"+bypass+"}' desconhecido para o {"+getClass().getSimpleName()+"}. Player: {"+player.getName()+"}");
- + }
- + catch (Exception e)
- + {
- + LOGGER.severe("Falha ao lidar com o bypass '{"+bypass+"}' do {"+getClass().getSimpleName()+"}. Player: {"+player.getName()+"} "+ e);
- + }
- + }
- +
- + public void showWaitingOrders(Player player)
- + {
- + showOrdersWindow(player, 1);
- + }
- +
- + public void showOrdersWindow(Player player, int page)
- + {
- + final List<WooOrder> products = getAccountOrders(player.getAccountName());
- + if (products.isEmpty())
- + return;
- +
- + final NpcHtmlMessage html = new NpcHtmlMessage(0);
- + html.setFile(HTML_PATH + "index.htm");
- +
- + final Pagination<WooOrder> pagination = new Pagination<>(products.stream(), page, 1, Comparator.comparing(WooOrder::getId, Comparator.reverseOrder()));
- + final WooOrder order = pagination.get(0);
- +
- + for (OrderProduct product : order.getProducts())
- + {
- + final String itemName = product.getItemCount() + " " + ItemTable.getInstance().getTemplate(product.getItemId()).getName();
- + pagination.append("<a action=\"bypass -h mb_order ", order.getId(), " ", product.getItemId(), " ", page, "\">", itemName , "</a><br>");
- + }
- +
- + if (pagination.getTotalEntries() > 1)
- + html.replace("%pages%", "<br>" + pagination.getPages("bypass mb_list %page%") + "<br>");
- + else
- + html.replace("%pages%", "");
- +
- + html.replace("%list%", pagination.getContent());
- + html.replace("%orderId%", order.getId());
- +
- + player.sendPacket(html);
- + }
- +
- + private class WooOrder
- + {
- + private final int _id;
- + private final List<OrderProduct> _products;
- +
- + public WooOrder(int orderId)
- + {
- + _id = orderId;
- + _products = new ArrayList<>();
- + }
- +
- + public WooOrder(int orderId, List<OrderProduct> products)
- + {
- + _id = orderId;
- + _products = products;
- + }
- +
- + public int getId()
- + {
- + return _id;
- + }
- +
- + public List<OrderProduct> getProducts()
- + {
- + return _products;
- + }
- + }
- +
- + private class OrderProduct
- + {
- + private final int _orderId;
- + private final int _itemId;
- + private final int _itemCount;
- + private final String _account;
- +
- + public OrderProduct(int orderId, int itemId, int itemCount, String account)
- + {
- + _orderId = orderId;
- + _itemId = itemId;
- + _itemCount = itemCount;
- + _account = account;
- + }
- +
- + public int getOrderId()
- + {
- + return _orderId;
- + }
- +
- + public int getItemId()
- + {
- + return _itemId;
- + }
- +
- + public int getItemCount()
- + {
- + return _itemCount;
- + }
- +
- + public String getAccount()
- + {
- + return _account;
- + }
- + }
- +
- + public static final WooOrdersManager getInstance()
- + {
- + return SingletonHolder._instance;
- + }
- +
- + private static class SingletonHolder
- + {
- + protected static final WooOrdersManager _instance = new WooOrdersManager();
- + }
- +}
- diff --git a/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java
- index 744703e..bfecbfd 100644
- --- a/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java
- +++ b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java
- @@ -45,11 +45,17 @@
- protected static final Logger _log = Logger.getLogger(LoginController.class.getName());
- // SQL Queries
- - private static final String USER_INFO_SELECT = "SELECT login, password, access_level, lastServer FROM accounts WHERE login=?";
- - private static final String AUTOCREATE_ACCOUNTS_INSERT = "INSERT INTO accounts (login, password, lastactive, access_level) values (?, ?, ?, ?)";
- - private static final String ACCOUNT_INFO_UPDATE = "UPDATE accounts SET lastactive = ? WHERE login = ?";
- - private static final String ACCOUNT_LAST_SERVER_UPDATE = "UPDATE accounts SET lastServer = ? WHERE login = ?";
- - private static final String ACCOUNT_ACCESS_LEVEL_UPDATE = "UPDATE accounts SET access_level = ? WHERE login = ?";
- + //private static final String USER_INFO_SELECT = "SELECT login, password, access_level, lastServer FROM accounts WHERE login=?";
- + private static final String AUTOCREATE_ACCOUNTS_INSERT = "INSERT INTO accounts (login, password, lastactive, access_level) values (?, ?, ?, ?)";
- + private static final String USER_INFO_SELECT = "SELECT login, password, access_level, lastServer,wp_user_id FROM accounts WHERE login = ?";
- + private static final String INSERT_ACCOUNT = "INSERT INTO accounts (login, password, lastactive, access_level,wp_user_id) values (?, ?, ?, ?,?)";
- +
- + private static final String ACCOUNT_INFO_UPDATE = "UPDATE accounts SET lastactive = ? WHERE login = ?";
- + private static final String ACCOUNT_LAST_SERVER_UPDATE = "UPDATE accounts SET lastServer = ? WHERE login = ?";
- + private static final String ACCOUNT_ACCESS_LEVEL_UPDATE = "UPDATE accounts SET access_level = ? WHERE login = ?";
- +
- + private static final String CHANGE_PASSWORD = "UPDATE accounts SET password=? WHERE login= ?";
- + private static final String SELECT_WP_ACCOUNT = "SELECT login FROM accounts WHERE wp_user_id = ?";
- private static LoginController _instance;
- @@ -171,7 +177,7 @@
- {
- if (rset.next())
- {
- - AccountInfo info = new AccountInfo(rset.getString("login"), rset.getString("password"), rset.getInt("access_level"), rset.getInt("lastServer"));
- + AccountInfo info = new AccountInfo(rset.getString("login"), rset.getString("password"), rset.getInt("access_level"), rset.getInt("lastServer"),rset.getInt("wp_user_id"));
- if (!info.checkPassHash(hashBase64))
- {
- // wrong password
- @@ -193,12 +199,13 @@
- }
- try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- - {
- + {
- PreparedStatement ps = con.prepareStatement(AUTOCREATE_ACCOUNTS_INSERT);
- ps.setString(1, login);
- ps.setString(2, hashBase64);
- ps.setLong(3, System.currentTimeMillis());
- ps.setInt(4, 0);
- + ps.setInt(5, 0);
- ps.execute();
- ps.close();
- }
- @@ -218,6 +225,9 @@
- }
- }
- +
- +
- +
- public AuthLoginResult tryCheckinAccount(LoginClient client, InetAddress address, AccountInfo info)
- {
- if (info.getAccessLevel() < 0)
- @@ -461,8 +471,114 @@
- }
- }
- +
- +
- public static LoginController getInstance()
- {
- return _instance;
- }
- +
- + /**WORDPRESS PANEL*/
- +
- + /**pioneer
- + * criacao de conta custom do wordpress
- + * criado outra funcao para nao atrapalhar chamadas em outras classes
- + * @param login
- + * @param hashed
- + * @param currentTime
- + * @param wpUserId wordpress id
- + * @return
- + */
- +
- + public AccountInfo createAccount(String login, String hashed, long currentTime, int wpUserId)
- + {
- +
- +
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(INSERT_ACCOUNT);
- + ps.setString(1, login);
- + ps.setString(2, hashed);
- + ps.setLong(3, System.currentTimeMillis());
- + ps.setInt(4, 0);
- + ps.setInt(5, wpUserId);
- + ps.execute();
- + ps.close();
- + }
- + catch (Exception e)
- + {
- + _log.log(Level.WARNING, "Exception while auto creating account for '" + login + "'!", e);
- + return null;
- + }
- +
- + // Generate a new Account.
- + return new AccountInfo(login, hashed, 0, 1, wpUserId);
- + }
- +
- +
- + public boolean changePassword(String newPass, String accountName)
- + {
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(CHANGE_PASSWORD);
- + ps.setString(1, newPass);
- + ps.setString(2, accountName);
- + ps.executeUpdate();
- + }
- + catch (Exception e)
- + {
- + _log.warning("Não foi possível alterar a senha de uma conta {"+accountName+"}. "+ e );
- + return false;
- + }
- +
- + return true;
- + }
- +
- + public AccountInfo getAccount(String login)
- + {
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(USER_INFO_SELECT);
- + ps.setString(1, login);
- +
- + try (ResultSet rs = ps.executeQuery())
- + {
- + if (rs.next())
- + return new AccountInfo(login, rs.getString("password"), rs.getInt("access_level"), rs.getInt("lastServer"),rs.getInt("wp_user_id"));
- + }
- + //ps.executeUpdate();
- + }
- + catch (Exception e)
- + {
- + _log.severe("Falha ao obter o login do usuario #"+login+" do Wordpress. "+ e );
- + }
- + return null;
- + }
- +
- + /**
- + * @param wpUserId : ID do usuário do wordpress
- + * @return Login da conta
- + */
- + public String getAccountLogin(int wpUserId)
- +
- + {
- + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
- + {
- + PreparedStatement ps = con.prepareStatement(SELECT_WP_ACCOUNT);
- + ps.setInt(1, wpUserId);
- +
- + try (ResultSet rs = ps.executeQuery())
- + {
- + if (rs.next())
- + return rs.getString("login");
- + }
- + ps.executeUpdate();
- + }
- + catch (Exception e)
- + {
- + _log.severe("Falha ao obter o login do usuário #"+wpUserId+" do Wordpress. "+ e );
- + }
- + return null;
- + }
- +
- }
- \ No newline at end of file
- diff --git a/aCis_gameserver/java/net/sf/l2j/loginserver/LoginMessageConsumer.java b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginMessageConsumer.java
- new file mode 100644
- index 0000000..b7c2238
- --- /dev/null
- +++ b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginMessageConsumer.java
- @@ -0,0 +1,168 @@
- +package net.sf.l2j.loginserver;
- +
- +import net.sf.l2j.commons.messagebroker.MBVariables;
- +import net.sf.l2j.commons.messagebroker.MessageBrokerHandler;
- +import net.sf.l2j.commons.messagebroker.AblyWebhook.*;
- +
- +import net.sf.l2j.Config;
- +import net.sf.l2j.loginserver.model.AccountInfo;
- +import net.sf.l2j.loginserver.model.GameServerInfo;
- +import net.sf.l2j.loginserver.network.LoginClient;
- +import net.sf.l2j.loginserver.network.serverpackets.LoginFail;
- +import net.sf.l2j.loginserver.network.serverpackets.LoginFail.LoginFailReason;
- +
- +public class LoginMessageConsumer extends MessageBrokerHandler
- +{
- + protected LoginMessageConsumer()
- + {
- + super(MBVariables.LS_SERVER_ENDPOINT, MBVariables.LS_QUEUE_NAME, MBVariables.LS_VHOST);
- + }
- +
- + @Override
- + protected void handleMessage(Envelope envelope)
- + {
- + try
- + {
- + final CustomerData customer = GSON.fromJson(envelope.getMessage(), CustomerData.class);
- + if (!validadeAuth(envelope.channel, customer))
- + return;
- +
- + switch (envelope.getChannel())
- + {
- + case "customer.updated":
- + updateAccount(customer);
- + break;
- +
- + case "customer.created":
- + createAccount(customer);
- + break;
- +
- + default:
- + LOGGER.warning("O canal '{"+envelope.getChannel()+"}' não possui um handler adequado no {"+getClass().getSimpleName()+"}.");
- + break;
- + }
- + }
- + catch (Exception e)
- + {
- + LOGGER.severe("Falha ao lidar com uma mensagem recebida pelo {"+getClass().getSimpleName()+"}. "+ e);
- + }
- + }
- +
- + /*
- + * Código de LoginController
- + */
- + @Override
- + protected void checkOnlineAccount(String username)
- + {
- + // Já está conectado no LoginServer
- + final LoginClient client = LoginController.getInstance().getAuthedClient(username);
- + if (client != null)
- + {
- + client.close(LoginFailReason.REASON_ACCOUNT_IN_USE);
- + LoginController.getInstance().removeAuthedLoginClient(username);
- + }
- +
- + // GameServer
- + final GameServerInfo gsi = LoginController.getInstance().getAccountOnGameServer(username);
- + if (gsi != null && gsi.isAuthed())
- + gsi.getGameServerThread().kickPlayer(username);
- + }
- +
- + /*
- + * Altera a senha ou o accessLevel de uma conta existente
- + */
- + private void updateAccount(CustomerData customer)
- + {
- + if (!validateAccount(customer))
- + return;
- +
- + // Se acontecer alguma alteração, podemos desconectar a conta depois
- + boolean accountChanged = false;
- +
- + // Senha foi alterada
- + if (customer.password_hash != null && !customer.password_hash.isEmpty())
- + {
- + final AccountInfo account = LoginController.getInstance().getAccount(customer.getUsername());
- + final String newPass = fixPasswordHash(customer.password_hash);
- +
- + if (!account.checkPassHash(newPass))
- + {
- + if (!LoginController.getInstance().changePassword(newPass, customer.getUsername()))
- + {
- + LOGGER.warning("Não foi possível realizar a troca de senha da conta '{"+customer.getUsername()+"}' solicitada pelo Wordpress.");
- + return;
- + }
- +
- + if (Config.DEVELOPER)
- + LOGGER.info("A alteração senha da conta '{"+customer.getUsername()+"}' solicitada pelo Wordpress foi realizada com sucesso.");
- +
- + accountChanged = true;
- + }
- + }
- +
- + // TODO Desativado no momento. Para criar um admin no jogo, é necessário definir o accessLevel do character, e não da conta. Mas como identificá-lo corretamente?
- + // final int accessLevel = MBVariables.CREATE_ADMIN ? (customer.role.equals("administrator") ? 8 : 0) : 0;
- + // if (account.getAccessLevel() >= 0 && account.getAccessLevel() != accessLevel)
- + // {
- + // AccountTable.getInstance().setAccountAccessLevel(customer.getUsername(), accessLevel);
- + //
- + // if (Config.DEVELOPER)
- + // LOGGER.info("A alteração do acessLevel da conta '{}' solicitada pelo Wordpress foi realizada.", customer.getUsername());
- + //
- + // accountChanged = true;
- + // }
- +
- + // Desconectar se estiver online
- + if (accountChanged && MBVariables.LOGOUT_ACCOUNT_CHANGE)
- + checkOnlineAccount(customer.getUsername());
- + }
- +
- + /*
- + * Cria uma nova conta com a possibilidade de definir o acessLevel para o level 8 (admin) caso o usuário tenha o privilégio de administrador no Wordpress.
- + */
- + private static void createAccount(CustomerData customer)
- + {
- + if (LoginController.getInstance().getAccount(customer.getUsername()) != null)
- + {
- + LOGGER.warning("A conta '"+customer.getUsername()+"' enviada pelo Wordpress já existe no servidor.");
- + return;
- + }
- +
- + if (customer.password_hash == null || customer.password_hash.isEmpty())
- + {
- + LOGGER.warning("Falha ao criar a conta '"+customer.getUsername()+"' enviada pelo Wordpress. Ela não possui senha." );
- + return;
- + }
- +
- + final String pass = fixPasswordHash(customer.password_hash);
- +// final int accessLevel = MBVariables.CREATE_ADMIN ? (customer.role.equals("administrator") ? 8 : 0) : 0;
- +
- + final AccountInfo account = LoginController.getInstance().createAccount(customer.getUsername(), pass, System.currentTimeMillis(), customer.getUserId());
- + if (account == null)
- + {
- + LOGGER.warning("Falha ao criar a conta '{}' enviada pelo Wordpress");
- + return;
- + }
- +
- + if (Config.DEVELOPER)
- + LOGGER.info("A conta '"+customer.getUsername()+"' enviada pelo Wordpress foi criada com sucesso.");
- + }
- +
- + /*
- + * O hash gerado pelo wp e o gerado pela acis tem essa pequena diferença
- + */
- + private static String fixPasswordHash(String wpPass)
- + {
- + return wpPass.replace("$2y$", "$2a$");
- + }
- +
- + public static final LoginMessageConsumer getInstance()
- + {
- + return SingletonHolder._instance;
- + }
- +
- + private static class SingletonHolder
- + {
- + protected static final LoginMessageConsumer _instance = new LoginMessageConsumer();
- + }
- +}
- diff --git a/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java b/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java
- index 9e2214c..ca6ce99 100644
- --- a/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java
- +++ b/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java
- @@ -8,8 +8,9 @@
- private final String _passHash;
- private final int _accessLevel;
- private final int _lastServer;
- + private final int _wpUserId;
- - public AccountInfo(final String login, final String passHash, final int accessLevel, final int lastServer)
- + public AccountInfo(final String login, final String passHash, final int accessLevel, final int lastServer,final int wpUserId)
- {
- Objects.requireNonNull(login, "login");
- Objects.requireNonNull(passHash, "passHash");
- @@ -24,6 +25,7 @@
- _passHash = passHash;
- _accessLevel = accessLevel;
- _lastServer = lastServer;
- + _wpUserId = wpUserId;
- }
- public boolean checkPassHash(final String passHash)
- @@ -45,4 +47,9 @@
- {
- return _lastServer;
- }
- +
- + public final int getWpUserId()
- + {
- + return _wpUserId;
- + }
- }
- \ No newline at end of file
Add Comment
Please, Sign In to add comment