pioneerr

WORDPRESS PAINEL ACIS 382

Mar 13th, 2025 (edited)
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 51.91 KB | None | 0 0
  1. diff --git a/aCis_gameserver/java/net/sf/l2j/Config.java b/aCis_gameserver/java/net/sf/l2j/Config.java
  2. index 49c4168..1083190 100644
  3. --- a/aCis_gameserver/java/net/sf/l2j/Config.java
  4. +++ b/aCis_gameserver/java/net/sf/l2j/Config.java
  5. @@ -797,6 +797,27 @@
  6. public static String[] CTF_TIMES_LIST;
  7. public static String[] DM_TIMES_LIST;
  8.  
  9. + /** PVP EVENT*/
  10. + public static String NAME_PVP;
  11. +
  12. + public static boolean PVP_EVENT_ENABLED;
  13. + public static String[] PVP_EVENT_INTERVAL;
  14. + public static int PVP_EVENT_RUNNING_TIME;
  15. + public static int[][] PVP_EVENT_REWARDS;
  16. + public static boolean ALLOW_SPECIAL_PVP_REWARD;
  17. + public static List<int[]> PVP_SPECIAL_ITEMS_REWARD;
  18. + public static boolean SCREN_MSG_PVP;
  19. + public static int pvp_locx;
  20. + public static int pvp_locy;
  21. + public static int pvp_locz;
  22. +
  23. + public static int PC_1x1;
  24. + public static int PC_PVP;
  25. + public static int MISSION_PVP_REWARD_ID;
  26. + public static int MISSION_PVP_REWARD_AMOUNT;
  27. + public static int MISSION_PVP_CONT;
  28. + public static boolean ACTIVE_MISSION_PVP;
  29. +
  30. /** Deathmatch event settings */
  31. public static boolean ALLOW_DM_EVENT;
  32. public static int DM_MIN_PLAYERS;
  33. diff --git a/aCis_gameserver/java/net/sf/l2j/commons/HttpClientApi.java b/aCis_gameserver/java/net/sf/l2j/commons/HttpClientApi.java
  34. new file mode 100644
  35. index 0000000..d8e3d73
  36. --- /dev/null
  37. +++ b/aCis_gameserver/java/net/sf/l2j/commons/HttpClientApi.java
  38. @@ -0,0 +1,116 @@
  39. +package net.sf.l2j.commons;
  40. +
  41. +import java.net.URI;
  42. +import java.net.http.HttpClient;
  43. +import java.net.http.HttpRequest;
  44. +import java.net.http.HttpRequest.Builder;
  45. +import java.net.http.HttpResponse;
  46. +import java.time.Duration;
  47. +import java.util.Map;
  48. +import java.util.concurrent.CompletableFuture;
  49. +
  50. +import java.util.logging.Logger;
  51. +
  52. +public class HttpClientApi
  53. +{
  54. +protected static final Logger LOGGER = null;
  55. +private static final HttpClient HTTPCLIENT = HttpClient.newBuilder()
  56. + .connectTimeout(Duration.ofSeconds(10)) // tempo para conectar-se
  57. + .version(HttpClient.Version.HTTP_2)
  58. + .build();
  59. +
  60. +public CompletableFuture<String> sendGetAsync(String url)
  61. +{
  62. + final HttpRequest request = HttpRequest.newBuilder()
  63. + .uri(URI.create(url))
  64. + .timeout(Duration.ofSeconds(10)) // tempo para resposta
  65. + .GET()
  66. + .build();
  67. +
  68. + return HTTPCLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
  69. + .thenApply(HttpResponse::body)
  70. + .exceptionally(e ->
  71. + {
  72. + LOGGER. warning("Erro na requisição GET async. "+e);
  73. + return null;
  74. + });
  75. +}
  76. +
  77. +public CompletableFuture<HttpResponse<String>> sendPostAsync(String url, String jsonBody)
  78. +{
  79. + return sendPostAsync(url, jsonBody, null);
  80. +}
  81. +
  82. +public CompletableFuture<HttpResponse<String>> sendPostAsync(String url, String jsonBody, Map<String, String> headers)
  83. +{
  84. + final Builder requestBuilder = HttpRequest.newBuilder()
  85. + .uri(URI.create(url))
  86. + .timeout(Duration.ofSeconds(10))
  87. + .header("Content-Type", "application/json")
  88. + .POST(HttpRequest.BodyPublishers.ofString(jsonBody));
  89. +
  90. + // Cabeçalhos adicionais
  91. + if (headers != null)
  92. + headers.forEach(requestBuilder::header);
  93. +
  94. + final HttpRequest request = requestBuilder.build();
  95. +
  96. + return HTTPCLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
  97. + .exceptionally(e ->
  98. + {
  99. + LOGGER. warning("Erro na requisição POST async. "+e);
  100. + return null;
  101. + });
  102. +}
  103. +
  104. +public String sendGet(String url)
  105. +{
  106. + final HttpRequest request = HttpRequest.newBuilder()
  107. + .uri(URI.create(url))
  108. + .timeout(Duration.ofSeconds(10))
  109. + .GET()
  110. + .build();
  111. +
  112. + try
  113. + {
  114. + final HttpResponse<String> response = HTTPCLIENT.send(request, HttpResponse.BodyHandlers.ofString());
  115. + return response.body();
  116. + }
  117. + catch (Exception e)
  118. + {
  119. + LOGGER. warning("Erro na requisição GET. "+e);
  120. + return null;
  121. + }
  122. +}
  123. +
  124. +public String sendPost(String url, String json)
  125. +{
  126. + final HttpRequest request = HttpRequest.newBuilder()
  127. + .uri(URI.create(url))
  128. + .timeout(Duration.ofSeconds(10))
  129. + .header("Content-Type", "application/json")
  130. + .POST(HttpRequest.BodyPublishers.ofString(json))
  131. + .build();
  132. +
  133. + try
  134. + {
  135. + final HttpResponse<String> response = HTTPCLIENT.send(request, HttpResponse.BodyHandlers.ofString());
  136. + return response.body();
  137. + }
  138. + catch (Exception e)
  139. + {
  140. + LOGGER. warning("Erro na requisição POST. "+e);
  141. + return null;
  142. + }
  143. +}
  144. +
  145. +public static HttpClientApi getInstance()
  146. +{
  147. + return SingletonHolder.INSTANCE;
  148. +}
  149. +
  150. +private static class SingletonHolder
  151. +{
  152. + protected static final HttpClientApi INSTANCE = new HttpClientApi();
  153. +}
  154. +}
  155. \ No newline at end of file
  156. diff --git a/aCis_gameserver/java/net/sf/l2j/commons/data/Pagination.java b/aCis_gameserver/java/net/sf/l2j/commons/data/Pagination.java
  157. new file mode 100644
  158. index 0000000..0029598
  159. --- /dev/null
  160. +++ b/aCis_gameserver/java/net/sf/l2j/commons/data/Pagination.java
  161. @@ -0,0 +1,155 @@
  162. +package net.sf.l2j.commons.data;
  163. +
  164. +import java.util.AbstractList;
  165. +import java.util.Collections;
  166. +import java.util.Comparator;
  167. +import java.util.List;
  168. +import java.util.function.Predicate;
  169. +import java.util.stream.IntStream;
  170. +import java.util.stream.Stream;
  171. +
  172. +import net.sf.l2j.commons.lang.StringUtil;
  173. +
  174. +public class Pagination<A> extends AbstractList<A>
  175. +{
  176. + private static final String NORMAL_LINE_SIZE = "<img height=17>";
  177. +
  178. + private final StringBuilder _content = new StringBuilder();
  179. +
  180. + private List<A> _list;
  181. + private int _page;
  182. + private int _limit;
  183. + private int _total;
  184. + private int _totalEntries;
  185. +
  186. + public Pagination(Stream<A> stream, int page, int limit)
  187. + {
  188. + this(stream, page, limit, null, null);
  189. + }
  190. +
  191. + public Pagination(Stream<A> stream, int page, int limit, Predicate<A> filter)
  192. + {
  193. + this(stream, page, limit, filter, null);
  194. + }
  195. +
  196. + public Pagination(Stream<A> stream, int page, int limit, Comparator<A> comparator)
  197. + {
  198. + this(stream, page, limit, null, comparator);
  199. + }
  200. +
  201. + public Pagination(Stream<A> stream, int page, int limit, Predicate<A> filter, Comparator<A> comparator)
  202. + {
  203. + _list = initList(stream, filter, comparator);
  204. + _totalEntries = _list.size();
  205. + _limit = Math.max(limit, 1);
  206. + _total = _list.size() / _limit + (_list.size() % _limit == 0 ? 0 : 1);
  207. + _page = Math.min(Math.max(page, 1), Math.max(1, _total));
  208. +
  209. +
  210. + if (_list.isEmpty())
  211. + return;
  212. +
  213. + _list = _list.subList((Math.min(page, _total) - 1) * limit, Math.min(Math.min(page, _total) * limit, _list.size()));
  214. + }
  215. +
  216. + private List<A> initList(Stream<A> stream, Predicate<A> filter, Comparator<A> comparator)
  217. + {
  218. + if (stream == null)
  219. + return Collections.emptyList();
  220. +
  221. + if (filter == null && comparator == null)
  222. + return stream.toList();
  223. +
  224. + if (comparator == null)
  225. + return stream.filter(filter).toList();
  226. +
  227. + if (filter == null)
  228. + return stream.sorted(comparator).toList();
  229. +
  230. + return stream.filter(filter).sorted(comparator).toList();
  231. + }
  232. +
  233. + public void append(Object... content)
  234. + {
  235. + StringUtil.append(_content, content);
  236. + }
  237. +
  238. + public void generateSpace()
  239. + {
  240. + IntStream.range(size(), _limit).forEach(x -> append(NORMAL_LINE_SIZE));
  241. + }
  242. +
  243. + public void generateSpace(int height)
  244. + {
  245. + IntStream.range(size(), _limit).forEach(x -> append("<img height=", height, ">"));
  246. + }
  247. +
  248. + public void generatePages(String action)
  249. + {
  250. + append(buildPages(action));
  251. + }
  252. +
  253. + public void generateSearch(String action, int height)
  254. + {
  255. + append("<table width=280 height=", height, "><tr>");
  256. + append("<td width=70 align=center>Search</td>");
  257. + append("<td width=140><edit var=\"search\" width=130 height=15></td>");
  258. + 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>");
  259. + append("</tr><tr>");
  260. + append("<td></td>");
  261. + append("<td align=center>Found ", _totalEntries, " results</td>");
  262. + append("<td></td>");
  263. + append("</tr></table>");
  264. + }
  265. +
  266. + public String getContent()
  267. + {
  268. + return _content.toString();
  269. + }
  270. +
  271. + public void resetContent()
  272. + {
  273. + _content.setLength(0);
  274. + }
  275. +
  276. + @Override
  277. + public A get(int index)
  278. + {
  279. + return _list.get(index);
  280. + }
  281. +
  282. + @Override
  283. + public int size()
  284. + {
  285. + return _list.size();
  286. + }
  287. +
  288. + public String getPages(String action)
  289. + {
  290. + return buildPages(action);
  291. + }
  292. +
  293. + private String buildPages(String action)
  294. + {
  295. + final StringBuilder sb = new StringBuilder();
  296. + 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>");
  297. +
  298. + for (int index = _page - 5; index < _page - 1; index++)
  299. + 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>");
  300. +
  301. + sb.append("<td FIXWIDTH=26 align=center><font color=LEVEL>" + String.format("%02d", Math.max(_page, 1)) + "</font></td>");
  302. +
  303. + for (int index = _page; index < _page + 4; index++)
  304. + 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>");
  305. +
  306. + 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>");
  307. + sb.append("<img src=\"L2UI.SquareGray\" width=280 height=1>");
  308. +
  309. + return sb.toString();
  310. + }
  311. +
  312. + public int getTotalEntries()
  313. + {
  314. + return _totalEntries;
  315. + }
  316. +}
  317. \ No newline at end of file
  318. diff --git a/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/AblyWebhook.java b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/AblyWebhook.java
  319. new file mode 100644
  320. index 0000000..602f120
  321. --- /dev/null
  322. +++ b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/AblyWebhook.java
  323. @@ -0,0 +1,83 @@
  324. +package net.sf.l2j.commons.messagebroker;
  325. +
  326. +import java.util.List;
  327. +import java.util.logging.Logger;
  328. +
  329. +import net.sf.l2j.loginserver.LoginController;
  330. +import net.sf.l2j.loginserver.model.AccountInfo;
  331. +
  332. +public class AblyWebhook
  333. +{
  334. + protected static final Logger LOGGER = Logger.getLogger(AblyWebhook.class.getName());
  335. +public static class Envelope
  336. +{
  337. + public String channel;
  338. + private List<Message> messages;
  339. +
  340. +
  341. + /**
  342. + * @return Nome do canal sem a identificação do namespace do Ably
  343. + */
  344. + public String getChannel()
  345. + {
  346. + return channel.replace("GS:", "").replace("LS:", "");
  347. + }
  348. +
  349. + /*
  350. + * Somente uma mensagem é trocada por vez
  351. + */
  352. + public String getMessage()
  353. + {
  354. + return messages.get(0).data;
  355. + }
  356. +}
  357. +
  358. +public static class Message
  359. +{
  360. + public String data;
  361. +}
  362. +
  363. +public static class CustomerData
  364. +{
  365. + public String code; // esse campo é enviado quando existe um problema de autenticação
  366. + private int id = -1; // id do usuário em customer.* e id da compra em order.*
  367. + private int customer_id = -1; // id do comprador em order.*
  368. + public String role;
  369. + private String username;
  370. + public String password_hash;
  371. + public String webhook_secrect;
  372. +
  373. + /*
  374. + * Em compras, o WooCommerce não envia o username, apenas o customer_id.
  375. + * Ao deletar um cliente, o WooCommerce está enviando somente o id do usuário
  376. + */
  377. + public String getUsername()
  378. + {
  379. + if (username == null)
  380. + username = LoginController.getInstance().getAccountLogin(getUserId());
  381. +
  382. + return username;
  383. + }
  384. +
  385. + public int getUserId()
  386. + {
  387. + return customer_id < 0 ? id : customer_id;
  388. + }
  389. +}
  390. +
  391. +public static class OrderData
  392. +{
  393. + public int id;
  394. + public int number;
  395. + public String status;
  396. + public List<ProductData> line_items;
  397. +}
  398. +
  399. +public static class ProductData
  400. +{
  401. + public String name;
  402. + public double price;
  403. + public int product_id;
  404. + public int quantity;
  405. +}
  406. +}
  407. \ No newline at end of file
  408. diff --git a/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MBVariables.java b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MBVariables.java
  409. new file mode 100644
  410. index 0000000..c26e8fe
  411. --- /dev/null
  412. +++ b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MBVariables.java
  413. @@ -0,0 +1,53 @@
  414. +package net.sf.l2j.commons.messagebroker;
  415. +
  416. +import java.util.HashMap;
  417. +import java.util.Map;
  418. +
  419. +public class MBVariables
  420. +{
  421. +// Ativar ou desativar. É necessário reinicar para alterar.
  422. +public static final boolean ENABLED = true;
  423. +
  424. +// Wordpress e WooCommerce
  425. +public static final String WP_SITE_URL = "http://l2jbrasil.com";
  426. +public static final String WC_CONSUMER_KEY = "ck_123213213213213213123123454354354354319b9a5";
  427. +public static final String WC_CONSUMER_SECRET = "ck_123213213213213213123123454354354354319b9a5";
  428. +
  429. +// Chave de API do Ably
  430. +public static final String ABLY_API_KEY = "shClSA.nNbwiA:gu_1Uf1232131231231234Sgn2LY";
  431. +
  432. +// Definir accessLevel 8 aos usuários que também são administradores no wordpress
  433. +// Isso permite criar ou definir admins no l2 a partir do painel
  434. +// public static final boolean CREATE_ADMIN = false;
  435. +
  436. +// Desconectar conta (se estiver online) ao alterar seus dados
  437. +public static final boolean LOGOUT_ACCOUNT_CHANGE = true;
  438. +
  439. +// Gameserver
  440. +public static final String LS_SERVER_ENDPOINT = "us-east-1-a-queue.ably.io:5671";
  441. +public static final String LS_QUEUE_NAME = "sh123A:loginserver";
  442. +public static final String LS_VHOST = "shared";
  443. +
  444. +// Loginserver
  445. +public static final String GS_SERVER_ENDPOINT = "us-east-1-a-queue.ably.io:5671";
  446. +public static final String GS_QUEUE_NAME = "shC123a:ameserver";
  447. +public static final String GS_VHOST = "shared";
  448. +
  449. +// Não mexa
  450. +public static final Map<Integer, Integer> PRODUCTS = new HashMap<>();
  451. +public static final Map<String, String> SECRETS = new HashMap<>();
  452. +
  453. +static
  454. +{
  455. + // Ao comprar um produto site, qual item o player deve receber?
  456. + // Para criar essa relação, insira o ID do produto do WooCommerce depois da vírgula o ID do item do L2
  457. + // Repita quantas vezes for necessário, mas uma relação por linha
  458. + PRODUCTS.put(354, 9527);
  459. + //PRODUCTS.put(1000, 3470);
  460. +
  461. + // Insira aqui os valores dos campos 'Segredo' de cada webhook do WooCommerce
  462. + SECRETS.put("LS:customer.created", "123122222222222VA:sICZ@$p_dqf!l");
  463. + SECRETS.put("LS:customer.updated", "I!t#{4#1222222222222222222");
  464. + SECRETS.put("GS:order.updated", "~Hf7uQec}ii12122222222222w#@s}wZn:x,8J");
  465. +}
  466. +}
  467. \ No newline at end of file
  468. diff --git a/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MessageBrokerHandler.java b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MessageBrokerHandler.java
  469. new file mode 100644
  470. index 0000000..c172b36
  471. --- /dev/null
  472. +++ b/aCis_gameserver/java/net/sf/l2j/commons/messagebroker/MessageBrokerHandler.java
  473. @@ -0,0 +1,151 @@
  474. +package net.sf.l2j.commons.messagebroker;
  475. +
  476. +import com.google.gson.Gson;
  477. +import com.rabbitmq.client.Channel;
  478. +import com.rabbitmq.client.Connection;
  479. +import com.rabbitmq.client.ConnectionFactory;
  480. +import com.rabbitmq.client.DeliverCallback;
  481. +
  482. +import java.util.logging.Logger;
  483. +
  484. +import net.sf.l2j.commons.messagebroker.AblyWebhook.CustomerData;
  485. +import net.sf.l2j.commons.messagebroker.AblyWebhook.Envelope;
  486. +
  487. +import net.sf.l2j.loginserver.model.AccountInfo;
  488. +import net.sf.l2j.loginserver.LoginController;
  489. +
  490. +public abstract class MessageBrokerHandler
  491. +{
  492. + protected static final Logger LOGGER = Logger.getLogger(MessageBrokerHandler.class.getName());
  493. +
  494. + protected static final Gson GSON = new Gson();
  495. +
  496. + private String _serverEndpoint;
  497. + private String _queueName;
  498. + private String _vHost;
  499. +
  500. + private Connection _connection;
  501. + private Channel _channel;
  502. +
  503. + protected MessageBrokerHandler(String serverEndpoint, String queueName, String vHost)
  504. + {
  505. + if (!MBVariables.ENABLED)
  506. + return;
  507. +
  508. + _serverEndpoint = serverEndpoint;
  509. + _queueName = queueName;
  510. + _vHost = vHost;
  511. +
  512. + start();
  513. + }
  514. +
  515. + private void start()
  516. + {
  517. + try
  518. + {
  519. + final ConnectionFactory factory = new ConnectionFactory();
  520. + factory.setUri("amqps://" + MBVariables.ABLY_API_KEY + "@" + _serverEndpoint + "/" + _vHost);
  521. + _connection = factory.newConnection();
  522. + _channel = _connection.createChannel();
  523. +
  524. + final DeliverCallback deliverCallback = (consumerTag, delivery) ->
  525. + {
  526. + String message = new String(delivery.getBody(), "UTF-8");
  527. + basicHandle(message);
  528. + };
  529. +
  530. + _channel.basicConsume(_queueName, true, deliverCallback, consumerTag -> {});
  531. +
  532. + LOGGER.info("{} started. "+getClass().getSimpleName());
  533. + }
  534. + catch (Exception e)
  535. + {
  536. + LOGGER.warning("Falha ao iniciar o {"+getClass().getSimpleName()+"}. "+ e);
  537. + }
  538. + }
  539. +
  540. + public void stop()
  541. + {
  542. + try
  543. + {
  544. + if (_channel != null && _channel.isOpen())
  545. + _channel.close();
  546. +
  547. + if (_connection != null && _connection.isOpen())
  548. + _connection.close();
  549. + }
  550. + catch (Exception e)
  551. + {
  552. + e.printStackTrace();
  553. + }
  554. + }
  555. +
  556. + protected abstract void handleMessage(Envelope envelope);
  557. +
  558. + /*
  559. + * O loginserver e o gameserver devem ser consultados através de seus próprios métodos
  560. + */
  561. + protected abstract void checkOnlineAccount(String username);
  562. +
  563. + private void basicHandle(String message)
  564. + {
  565. + try
  566. + {
  567. + final Envelope envelope = GSON.fromJson(message, Envelope.class);
  568. + handleMessage(envelope);
  569. + }
  570. + catch (Exception e)
  571. + {
  572. + LOGGER.warning("Falha ao desserializar mensagem recebida no "+getClass().getSimpleName()+". "+ e);
  573. + }
  574. + }
  575. +
  576. + protected boolean validadeAuth(String channel, CustomerData customer)
  577. + {
  578. + // 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
  579. + if (customer.code != null)
  580. + {
  581. + LOGGER.warning("O webhook "+ channel+" não está enviando os dados corretamente. Delete o atual e crie um novo. ");
  582. + return false;
  583. + }
  584. +
  585. + if (!MBVariables.SECRETS.containsKey(channel) || !MBVariables.SECRETS.get(channel).equals(customer.webhook_secrect))
  586. + {
  587. +
  588. + LOGGER.warning("Falha ao verificar o segredo do canal "+channel+" do "+getClass().getSimpleName()+".");
  589. + return false;
  590. + }
  591. +
  592. + return true;
  593. + }
  594. +
  595. + /*
  596. + * O AccountInfo é o nosso custom, mas não verificamos porque ele é criado junto a conta, e está no Gameserver.
  597. + */
  598. + protected boolean validateAccount(CustomerData customer)
  599. + {
  600. + if (customer.getUsername() == null)
  601. + return false;
  602. +
  603. + final AccountInfo account = LoginController.getInstance().getAccount(customer.getUsername());
  604. +
  605. + if (account == null)
  606. + {
  607. + LOGGER.warning("A conta '"+customer.getUsername()+"' enviada pelo Wordpress não existe no servidor.");
  608. + return false;
  609. + }
  610. +
  611. + if (account.getWpUserId() != customer.getUserId())
  612. + {
  613. + LOGGER.warning("A conta '"+customer.getUsername()+"' enviada pelo Wordpress não é a mesma que existe no servidor.");
  614. + return false;
  615. + }
  616. +
  617. + return true;
  618. + }
  619. +
  620. + protected Gson getGson()
  621. + {
  622. + return GSON;
  623. + }
  624. +}
  625. diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java b/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java
  626. index 0c9fb95..4415c8c 100644
  627. --- a/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java
  628. +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/GameServer.java
  629. @@ -14,6 +14,8 @@
  630.  
  631. import net.sf.l2j.Config;
  632. import net.sf.l2j.L2DatabaseFactory;
  633. +
  634. +import net.sf.l2j.commons.HttpClientApi;
  635. import net.sf.l2j.commons.concurrent.ThreadPool;
  636. import net.sf.l2j.commons.lang.StringUtil;
  637. import net.sf.l2j.commons.mmocore.SelectorConfig;
  638. @@ -122,6 +124,7 @@
  639. import net.sf.l2j.gameserver.taskmanager.ShadowItemTaskManager;
  640. import net.sf.l2j.gameserver.taskmanager.WaterTaskManager;
  641. import net.sf.l2j.gameserver.xmlfactory.XMLDocumentFactory;
  642. +import net.sf.l2j.loginserver.LoginController;
  643. import net.sf.l2j.util.DeadLockDetector;
  644. import net.sf.l2j.util.IPv4Filter;
  645.  
  646. @@ -205,13 +208,22 @@
  647. /** Party Farm Event */
  648. StringUtil.printSection("Party Farm Event");
  649. _log.info("Evento Party Farm");
  650. - if (Config.PARTY_FARM_BY_TIME_OF_DAY && !Config.START_PARTY) {
  651. + /*if (Config.PARTY_FARM_BY_TIME_OF_DAY && !Config.START_PARTY) {
  652. InitialPartyFarm.getInstance().StartCalculationOfNextEventTime();
  653. _log.info("[Party Farm Time]: Enabled");
  654. } else if (Config.START_PARTY && !Config.PARTY_FARM_BY_TIME_OF_DAY) {
  655. _log.info("[Start Spawn Party Farm]: Enabled");
  656. ThreadPool.schedule(new SpawnMonsters(), Config.NPC_SERVER_DELAY * 1000L);
  657. - }
  658. + } */
  659. + if ((Config.START_PARTY))
  660. + {
  661. + _log.info("[Party Farm Time]: Enabled");
  662. + InitialPartyFarm.getInstance().StartCalculationOfNextEventTime();
  663. + }
  664. + else
  665. + {
  666. + _log.info("Party Farm is disabled.");
  667. + }
  668.  
  669. /** Tournament 2x2 4x4 9x9*/
  670. StringUtil.printSection("Tournament 2x2 4x4 9x9");
  671. @@ -369,6 +381,12 @@
  672. BoatTalkingGludin.load();
  673. }
  674.  
  675. + StringUtil.printSection("WORDPRESS - Message Broker");
  676. + LoginController.load();
  677. + HttpClientApi.getInstance();
  678. + GameMessageConsumer.getInstance();
  679. +
  680. +
  681. StringUtil.printSection("Events");
  682. DerbyTrackManager.getInstance();
  683. LotteryManager.getInstance();
  684. @@ -475,7 +493,7 @@
  685. return _selectorThread;
  686. }
  687.  
  688. - public class SpawnMonsters implements Runnable
  689. + /*public class SpawnMonsters implements Runnable
  690. {
  691. public SpawnMonsters()
  692. {
  693. @@ -489,5 +507,5 @@
  694.  
  695. PartyFarm.spawnMonsters();
  696. }
  697. - }
  698. + } */
  699. }
  700. \ No newline at end of file
  701. 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
  702. index 4953582..7289497 100644
  703. --- a/aCis_gameserver/java/net/sf/l2j/gameserver/data/sql/PlayerInfoTable.java
  704. +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/data/sql/PlayerInfoTable.java
  705. @@ -3,6 +3,7 @@
  706. import java.sql.Connection;
  707. import java.sql.PreparedStatement;
  708. import java.sql.ResultSet;
  709. +import java.util.List;
  710. import java.sql.SQLException;
  711. import java.util.Map;
  712. import java.util.Map.Entry;
  713. @@ -186,4 +187,9 @@
  714. {
  715. protected static final PlayerInfoTable INSTANCE = new PlayerInfoTable();
  716. }
  717. +
  718. + public final List<Integer> getAccountCharacters(String accountName)
  719. + {
  720. + return _infos.entrySet().stream().filter(m -> m.getValue().getAccountName().equalsIgnoreCase(accountName)).map(Entry::getKey).toList();
  721. + }
  722. }
  723. \ No newline at end of file
  724. 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
  725. index 23d55bb..a06b388 100644
  726. --- a/aCis_gameserver/java/net/sf/l2j/gameserver/model/actor/Player.java
  727. +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/model/actor/Player.java
  728. @@ -22,6 +22,7 @@
  729. import java.util.concurrent.locks.ReentrantLock;
  730. import java.util.logging.Level;
  731. import java.util.stream.Collectors;
  732. +import java.util.List;
  733.  
  734. import net.sf.l2j.commons.concurrent.ThreadPool;
  735. import net.sf.l2j.commons.math.MathUtil;
  736. @@ -264,6 +265,8 @@
  737.  
  738. import net.sf.l2j.gameserver.model.actor.instance.Agathion;
  739.  
  740. +import net.sf.l2j.gameserver.wordpress.WooOrdersManager;
  741. +
  742. /**
  743. * This class represents a player in the world.<br>
  744. * There is always a client-thread connected to this (except if a player-store is activated upon logout).
  745. @@ -8426,6 +8429,8 @@
  746.  
  747. revalidateZone(true);
  748. notifyFriends(true);
  749. + // Verificar se existe alguma compra pendente para ser entregue
  750. + WooOrdersManager.getInstance().showWaitingOrders(this);
  751. }
  752.  
  753. public long getLastAccess()
  754. @@ -11303,5 +11308,7 @@
  755. {
  756. return aga;
  757. }
  758. +
  759. +
  760.  
  761. }
  762. \ No newline at end of file
  763. diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooCommerceAPI.java b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooCommerceAPI.java
  764. new file mode 100644
  765. index 0000000..526f484
  766. --- /dev/null
  767. +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooCommerceAPI.java
  768. @@ -0,0 +1,53 @@
  769. +package net.sf.l2j.gameserver.wordpress;
  770. +
  771. +import com.google.gson.JsonObject;
  772. +
  773. +import java.util.Base64;
  774. +import java.util.Map;
  775. +import java.util.logging.Logger;
  776. +
  777. +import net.sf.l2j.commons.HttpClientApi;
  778. +import net.sf.l2j.commons.messagebroker.MBVariables;
  779. +
  780. +public class WooCommerceAPI
  781. +{
  782. + private static final Logger LOGGER = Logger.getLogger(WooCommerceAPI.class.getName());
  783. +
  784. + private static String getAuthHeader()
  785. + {
  786. + final String authString = MBVariables.WC_CONSUMER_KEY + ":" + MBVariables.WC_CONSUMER_SECRET;
  787. + return "Basic " + Base64.getEncoder().encodeToString(authString.getBytes());
  788. + }
  789. +
  790. + private static String getApiUrl()
  791. + {
  792. + return MBVariables.WP_SITE_URL + "/wp-json/wc/v3/";
  793. + }
  794. +
  795. + public void addOrderNote(int orderId, boolean customerNote, String message)
  796. + {
  797. + final String url = getApiUrl() + "orders/" + orderId + "/notes";
  798. + final JsonObject json = new JsonObject();
  799. +
  800. + json.addProperty("note", message);
  801. + json.addProperty("customer_note", customerNote);
  802. +
  803. + HttpClientApi.getInstance()
  804. + .sendPostAsync(url, json.toString(), Map.of("Authorization", getAuthHeader()))
  805. + .thenAccept(response ->
  806. + {
  807. + if (response.statusCode() != 200 && response.statusCode() != 201)
  808. + LOGGER.warning("Não foi possível adicionar uma nota na Order #"+orderId+" do WooCommerce. StatusCode: "+response.statusCode());
  809. + });
  810. + }
  811. +
  812. + public static WooCommerceAPI getInstance()
  813. + {
  814. + return SingletonHolder.INSTANCE;
  815. + }
  816. +
  817. + private static class SingletonHolder
  818. + {
  819. + protected static final WooCommerceAPI INSTANCE = new WooCommerceAPI();
  820. + }
  821. +}
  822. diff --git a/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooOrdersManager.java b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooOrdersManager.java
  823. new file mode 100644
  824. index 0000000..825d1af
  825. --- /dev/null
  826. +++ b/aCis_gameserver/java/net/sf/l2j/gameserver/wordpress/WooOrdersManager.java
  827. @@ -0,0 +1,395 @@
  828. +package net.sf.l2j.gameserver.wordpress;
  829. +
  830. +import java.sql.Connection;
  831. +import java.sql.PreparedStatement;
  832. +import java.sql.ResultSet;
  833. +import java.util.ArrayList;
  834. +import java.util.Comparator;
  835. +import java.util.List;
  836. +import java.util.Map;
  837. +import java.util.StringTokenizer;
  838. +import java.util.concurrent.ConcurrentHashMap;
  839. +import java.util.logging.Logger;
  840. +
  841. +import net.sf.l2j.commons.data.Pagination;
  842. +import net.sf.l2j.commons.messagebroker.MBVariables;
  843. +import net.sf.l2j.commons.messagebroker.MessageBrokerHandler;
  844. +import net.sf.l2j.commons.messagebroker.AblyWebhook.CustomerData;
  845. +import net.sf.l2j.commons.messagebroker.AblyWebhook.OrderData;
  846. +import net.sf.l2j.commons.messagebroker.AblyWebhook.ProductData;
  847. +
  848. +import net.sf.l2j.Config;
  849. +import net.sf.l2j.L2DatabaseFactory;
  850. +import net.sf.l2j.gameserver.data.ItemTable;
  851. +import net.sf.l2j.gameserver.data.sql.PlayerInfoTable;
  852. +import net.sf.l2j.gameserver.data.ItemTable;
  853. +import net.sf.l2j.gameserver.model.World;
  854. +import net.sf.l2j.gameserver.model.actor.Player;
  855. +import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
  856. +import net.sf.l2j.loginserver.model.AccountInfo;
  857. +
  858. +public class WooOrdersManager
  859. +{
  860. + private static final Logger LOGGER = Logger.getLogger(WooOrdersManager.class.getName());
  861. +
  862. + private static final String HTML_PATH = "data/html/mods/MessageBroker/";
  863. +
  864. + private static final String LOAD_ORDERS = "SELECT * from mb_woo_orders";
  865. + private static final String INSERT_ORDER = "INSERT INTO mb_woo_orders (`order_id`,`item_id`,`item_count`,`account`) VALUES (?,?,?,?)";
  866. + private static final String DELETE_ORDER = "DELETE FROM mb_woo_orders WHERE order_id=? AND account=?";
  867. + private static final String DELETE_PRODUCT = "DELETE FROM mb_woo_orders WHERE order_id=? AND item_id=? AND account=?";
  868. + private static final String CLEAR_ACCOUNT = "DELETE FROM mb_woo_orders WHERE account=?";
  869. +
  870. + private final Map<String, List<WooOrder>> _orders = new ConcurrentHashMap<>();
  871. +
  872. + public WooOrdersManager()
  873. + {
  874. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  875. + {
  876. + PreparedStatement ps = con.prepareStatement(LOAD_ORDERS);
  877. +
  878. + try (ResultSet rs = ps.executeQuery())
  879. + {
  880. + while (rs.next())
  881. + {
  882. + final String account = rs.getString("account");
  883. + final int orderId = rs.getInt("order_id");
  884. + WooOrder order = getOrder(account, orderId);
  885. +
  886. + if (order == null)
  887. + {
  888. + order = new WooOrder(orderId);
  889. + getAccountOrders(account).add(order);
  890. + }
  891. +
  892. + order.getProducts().add(new OrderProduct(orderId, rs.getInt("item_id"), rs.getInt("item_count"), account));
  893. + }
  894. + }
  895. + if (!_orders.isEmpty())
  896. + LOGGER.info(_orders.values().size() + " compras estão prontas aguardando o recebimento pelos players.");
  897. + }
  898. + catch (Exception e)
  899. + {
  900. + LOGGER.severe("Não foi possível restaurar as compras do WooCommerce. "+e);
  901. + }
  902. +
  903. +
  904. + }
  905. +
  906. + public List<WooOrder> getAccountOrders(String account)
  907. + {
  908. + return _orders.computeIfAbsent(account, k -> new ArrayList<>());
  909. + }
  910. +
  911. + private WooOrder getOrder(String account, int orderId)
  912. + {
  913. + return getOrder(account, orderId, false);
  914. + }
  915. +
  916. + private WooOrder getOrder(String account, int orderId, boolean create)
  917. + {
  918. + return getAccountOrders(account).stream().filter(o -> o.getId() == orderId).findFirst().orElse(create ? new WooOrder(orderId) : null);
  919. + }
  920. +
  921. + private OrderProduct getOrderProduct(String account, int orderId, int itemId)
  922. + {
  923. + return getOrder(account, orderId).getProducts().stream().filter(p -> p.getItemId() == itemId).findFirst().orElse(null);
  924. + }
  925. +
  926. + private boolean insertOrder(String account, int orderId, List<OrderProduct> products)
  927. + {
  928. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  929. + {
  930. + PreparedStatement ps = con.prepareStatement(INSERT_ORDER);
  931. + for (OrderProduct product : products)
  932. + {
  933. + ps.setInt(1, product.getOrderId());
  934. + ps.setInt(2, product.getItemId());
  935. + ps.setInt(3, product.getItemCount());
  936. + ps.setString(4, product.getAccount());
  937. + ps.addBatch();
  938. + }
  939. + ps.executeBatch();
  940. +
  941. + getAccountOrders(account).add(new WooOrder(orderId, products));
  942. + }
  943. + catch (Exception e)
  944. + {
  945. + LOGGER.severe("Não foi possível inserir no banco de dados a Order #{"+orderId+"} da conta '{"+account+"}' do WooCommerce."+ e);
  946. + return false;
  947. + }
  948. +
  949. + return true;
  950. + }
  951. +
  952. + private boolean deleteOrder(String account, int orderId)
  953. + {
  954. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  955. + {
  956. + PreparedStatement ps = con.prepareStatement(DELETE_ORDER);
  957. + {
  958. + ps.setInt(1, orderId);
  959. + ps.setString(2, account);
  960. + ps.execute();
  961. +
  962. + getAccountOrders(account).removeIf(o -> o.getId() == orderId);
  963. + }
  964. +
  965. + }
  966. + catch (Exception e)
  967. + {
  968. + LOGGER.severe("Não foi possível deletar do banco de dados a Order #"+orderId+" do WooCommerce. "+ e );
  969. + return false;
  970. + }
  971. +
  972. + return true;
  973. + }
  974. +
  975. + private boolean deleteProduct(String account, OrderProduct product)
  976. + {
  977. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  978. + {
  979. + PreparedStatement ps = con.prepareStatement(DELETE_PRODUCT);
  980. + ps.setInt(1, product.getOrderId());
  981. + ps.setInt(2, product.getItemId());
  982. + ps.setString(3, account);
  983. + ps.execute();
  984. +
  985. + final WooOrder order = getOrder(account, product.getOrderId());
  986. + order.getProducts().remove(product);
  987. +
  988. + if (order.getProducts().isEmpty())
  989. + getAccountOrders(account).remove(order);
  990. + }
  991. + catch (Exception e)
  992. + {
  993. + LOGGER.severe("Não foi possível deletar do banco de dados o item #"+product.getItemId()+" da Order #"+product.getOrderId()+" do WooCommerce. "+ e );
  994. + return false;
  995. + }
  996. + return true;
  997. + }
  998. +
  999. + /**
  1000. + * Apaga todas as compras pendentes da conta especificada. Utilizado na exclusão de contas.
  1001. + * Importante para evitar que uma compras não recebidas de uma conta deletada sejam entregues a outra criada com o mesmo login.
  1002. + * @param account : login da conta
  1003. + */
  1004. + public void clearAccount(String account)
  1005. + {
  1006. + getAccountOrders(account).clear();
  1007. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1008. + {
  1009. + PreparedStatement ps = con.prepareStatement(CLEAR_ACCOUNT);
  1010. + ps.setString(1, account);
  1011. + ps.execute();
  1012. +
  1013. + }
  1014. + catch (Exception e)
  1015. + {
  1016. + LOGGER.severe("Não foi possível limpar as compras do WooCommerce da conta {"+account+"}. "+ e );
  1017. + }
  1018. +
  1019. + }
  1020. +
  1021. + public void onCompletedOrder(CustomerData customer, OrderData order)
  1022. + {
  1023. + if (order.line_items == null || order.line_items.isEmpty())
  1024. + return;
  1025. +
  1026. + final List<OrderProduct> orderProducts = new ArrayList<>();
  1027. + for (ProductData product : order.line_items)
  1028. + {
  1029. + if (!MBVariables.PRODUCTS.containsKey(product.product_id))
  1030. + {
  1031. + 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." );
  1032. + return;
  1033. + }
  1034. +
  1035. + final int itemId = MBVariables.PRODUCTS.get(product.product_id);
  1036. + orderProducts.add(new OrderProduct(order.id, itemId, product.quantity, customer.getUsername()));
  1037. + }
  1038. +
  1039. + if (insertOrder(customer.getUsername(), order.id, orderProducts))
  1040. + {
  1041. + // Notificar se algum player estiver online para receber
  1042. + for (int playerId : PlayerInfoTable.getInstance().getAccountCharacters(customer.getUsername()))
  1043. + {
  1044. + final Player player = World.getInstance().getPlayer(playerId);
  1045. + if (player != null && player.isOnline())
  1046. + {
  1047. + showWaitingOrders(player);
  1048. + break;
  1049. + }
  1050. + }
  1051. +
  1052. + // Adicionar notificação para o usuário e o painel WordPress
  1053. + WooCommerceAPI.getInstance().addOrderNote(order.id, true, "Compra concluído com sucesso. Os itens já estão disponvéis na sua conta.");
  1054. +
  1055. + if (Config.DEVELOPER)
  1056. + LOGGER.warning("A Order #{"+order.id+"} realizada no WooCommerce foi recebida com sucesso.");
  1057. + }
  1058. + }
  1059. +
  1060. + /*
  1061. + * SE a compra foi reembolsada (cancelada), então verificamos se os itens já foram entregues.
  1062. + * 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.
  1063. + */
  1064. + public void onCancelledOrder(CustomerData customer, OrderData order)
  1065. + {
  1066. + // Não recebemos essa compra ou ela já foi resgatada pelo player.
  1067. + final WooOrder wooOrder = getOrder(customer.getUsername(), order.id);
  1068. + if (wooOrder == null)
  1069. + return;
  1070. +
  1071. + if (deleteOrder(customer.getUsername(), order.id))
  1072. + {
  1073. + WooCommerceAPI.getInstance().addOrderNote(order.id, true, "A compra foi cancelada. Os itens não estão mais disponíveis.");
  1074. +
  1075. + if (Config.DEVELOPER)
  1076. + LOGGER.warning("A solicitação de cancelamento da Order #{"+ order.id+"} realizada no WooCommerce foi recebida com sucesso.");
  1077. + }
  1078. + }
  1079. +
  1080. + public void deliverOrderProduct(Player player, int orderId, int itemId, int page)
  1081. + {
  1082. + final OrderProduct product = getOrderProduct(player.getAccountName(), orderId, itemId);
  1083. + if (product == null)
  1084. + return;
  1085. +
  1086. + if (deleteProduct(player.getAccountName(), product))
  1087. + player.addItem("Item add.",product.getItemId(), product.getItemCount(),null, true);
  1088. +
  1089. + showOrdersWindow(player, page);
  1090. + }
  1091. +
  1092. + public void handleBypass(Player player, String bypass)
  1093. + {
  1094. + try
  1095. + {
  1096. + if (!player.validateBypass(bypass))
  1097. + return;
  1098. +
  1099. + final StringTokenizer st = new StringTokenizer(bypass.substring(3)); // mb_
  1100. + final String action = st.nextToken();
  1101. +
  1102. + if (action.equals("list"))
  1103. + showOrdersWindow(player, Integer.valueOf(st.nextToken()));
  1104. + else if (action.equals("order"))
  1105. + deliverOrderProduct(player, Integer.valueOf(st.nextToken()), Integer.valueOf(st.nextToken()), Integer.valueOf(st.nextToken()));
  1106. + else
  1107. + LOGGER.warning("Bypass '{"+bypass+"}' desconhecido para o {"+getClass().getSimpleName()+"}. Player: {"+player.getName()+"}");
  1108. + }
  1109. + catch (Exception e)
  1110. + {
  1111. + LOGGER.severe("Falha ao lidar com o bypass '{"+bypass+"}' do {"+getClass().getSimpleName()+"}. Player: {"+player.getName()+"} "+ e);
  1112. + }
  1113. + }
  1114. +
  1115. + public void showWaitingOrders(Player player)
  1116. + {
  1117. + showOrdersWindow(player, 1);
  1118. + }
  1119. +
  1120. + public void showOrdersWindow(Player player, int page)
  1121. + {
  1122. + final List<WooOrder> products = getAccountOrders(player.getAccountName());
  1123. + if (products.isEmpty())
  1124. + return;
  1125. +
  1126. + final NpcHtmlMessage html = new NpcHtmlMessage(0);
  1127. + html.setFile(HTML_PATH + "index.htm");
  1128. +
  1129. + final Pagination<WooOrder> pagination = new Pagination<>(products.stream(), page, 1, Comparator.comparing(WooOrder::getId, Comparator.reverseOrder()));
  1130. + final WooOrder order = pagination.get(0);
  1131. +
  1132. + for (OrderProduct product : order.getProducts())
  1133. + {
  1134. + final String itemName = product.getItemCount() + " " + ItemTable.getInstance().getTemplate(product.getItemId()).getName();
  1135. + pagination.append("<a action=\"bypass -h mb_order ", order.getId(), " ", product.getItemId(), " ", page, "\">", itemName , "</a><br>");
  1136. + }
  1137. +
  1138. + if (pagination.getTotalEntries() > 1)
  1139. + html.replace("%pages%", "<br>" + pagination.getPages("bypass mb_list %page%") + "<br>");
  1140. + else
  1141. + html.replace("%pages%", "");
  1142. +
  1143. + html.replace("%list%", pagination.getContent());
  1144. + html.replace("%orderId%", order.getId());
  1145. +
  1146. + player.sendPacket(html);
  1147. + }
  1148. +
  1149. + private class WooOrder
  1150. + {
  1151. + private final int _id;
  1152. + private final List<OrderProduct> _products;
  1153. +
  1154. + public WooOrder(int orderId)
  1155. + {
  1156. + _id = orderId;
  1157. + _products = new ArrayList<>();
  1158. + }
  1159. +
  1160. + public WooOrder(int orderId, List<OrderProduct> products)
  1161. + {
  1162. + _id = orderId;
  1163. + _products = products;
  1164. + }
  1165. +
  1166. + public int getId()
  1167. + {
  1168. + return _id;
  1169. + }
  1170. +
  1171. + public List<OrderProduct> getProducts()
  1172. + {
  1173. + return _products;
  1174. + }
  1175. + }
  1176. +
  1177. + private class OrderProduct
  1178. + {
  1179. + private final int _orderId;
  1180. + private final int _itemId;
  1181. + private final int _itemCount;
  1182. + private final String _account;
  1183. +
  1184. + public OrderProduct(int orderId, int itemId, int itemCount, String account)
  1185. + {
  1186. + _orderId = orderId;
  1187. + _itemId = itemId;
  1188. + _itemCount = itemCount;
  1189. + _account = account;
  1190. + }
  1191. +
  1192. + public int getOrderId()
  1193. + {
  1194. + return _orderId;
  1195. + }
  1196. +
  1197. + public int getItemId()
  1198. + {
  1199. + return _itemId;
  1200. + }
  1201. +
  1202. + public int getItemCount()
  1203. + {
  1204. + return _itemCount;
  1205. + }
  1206. +
  1207. + public String getAccount()
  1208. + {
  1209. + return _account;
  1210. + }
  1211. + }
  1212. +
  1213. + public static final WooOrdersManager getInstance()
  1214. + {
  1215. + return SingletonHolder._instance;
  1216. + }
  1217. +
  1218. + private static class SingletonHolder
  1219. + {
  1220. + protected static final WooOrdersManager _instance = new WooOrdersManager();
  1221. + }
  1222. +}
  1223. diff --git a/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java
  1224. index 744703e..bfecbfd 100644
  1225. --- a/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java
  1226. +++ b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginController.java
  1227. @@ -45,11 +45,17 @@
  1228. protected static final Logger _log = Logger.getLogger(LoginController.class.getName());
  1229.  
  1230. // SQL Queries
  1231. - private static final String USER_INFO_SELECT = "SELECT login, password, access_level, lastServer FROM accounts WHERE login=?";
  1232. - private static final String AUTOCREATE_ACCOUNTS_INSERT = "INSERT INTO accounts (login, password, lastactive, access_level) values (?, ?, ?, ?)";
  1233. - private static final String ACCOUNT_INFO_UPDATE = "UPDATE accounts SET lastactive = ? WHERE login = ?";
  1234. - private static final String ACCOUNT_LAST_SERVER_UPDATE = "UPDATE accounts SET lastServer = ? WHERE login = ?";
  1235. - private static final String ACCOUNT_ACCESS_LEVEL_UPDATE = "UPDATE accounts SET access_level = ? WHERE login = ?";
  1236. + //private static final String USER_INFO_SELECT = "SELECT login, password, access_level, lastServer FROM accounts WHERE login=?";
  1237. + private static final String AUTOCREATE_ACCOUNTS_INSERT = "INSERT INTO accounts (login, password, lastactive, access_level) values (?, ?, ?, ?)";
  1238. + private static final String USER_INFO_SELECT = "SELECT login, password, access_level, lastServer,wp_user_id FROM accounts WHERE login = ?";
  1239. + private static final String INSERT_ACCOUNT = "INSERT INTO accounts (login, password, lastactive, access_level,wp_user_id) values (?, ?, ?, ?,?)";
  1240. +
  1241. + private static final String ACCOUNT_INFO_UPDATE = "UPDATE accounts SET lastactive = ? WHERE login = ?";
  1242. + private static final String ACCOUNT_LAST_SERVER_UPDATE = "UPDATE accounts SET lastServer = ? WHERE login = ?";
  1243. + private static final String ACCOUNT_ACCESS_LEVEL_UPDATE = "UPDATE accounts SET access_level = ? WHERE login = ?";
  1244. +
  1245. + private static final String CHANGE_PASSWORD = "UPDATE accounts SET password=? WHERE login= ?";
  1246. + private static final String SELECT_WP_ACCOUNT = "SELECT login FROM accounts WHERE wp_user_id = ?";
  1247.  
  1248. private static LoginController _instance;
  1249.  
  1250. @@ -171,7 +177,7 @@
  1251. {
  1252. if (rset.next())
  1253. {
  1254. - AccountInfo info = new AccountInfo(rset.getString("login"), rset.getString("password"), rset.getInt("access_level"), rset.getInt("lastServer"));
  1255. + AccountInfo info = new AccountInfo(rset.getString("login"), rset.getString("password"), rset.getInt("access_level"), rset.getInt("lastServer"),rset.getInt("wp_user_id"));
  1256. if (!info.checkPassHash(hashBase64))
  1257. {
  1258. // wrong password
  1259. @@ -193,12 +199,13 @@
  1260. }
  1261.  
  1262. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1263. - {
  1264. + {
  1265. PreparedStatement ps = con.prepareStatement(AUTOCREATE_ACCOUNTS_INSERT);
  1266. ps.setString(1, login);
  1267. ps.setString(2, hashBase64);
  1268. ps.setLong(3, System.currentTimeMillis());
  1269. ps.setInt(4, 0);
  1270. + ps.setInt(5, 0);
  1271. ps.execute();
  1272. ps.close();
  1273. }
  1274. @@ -218,6 +225,9 @@
  1275. }
  1276. }
  1277.  
  1278. +
  1279. +
  1280. +
  1281. public AuthLoginResult tryCheckinAccount(LoginClient client, InetAddress address, AccountInfo info)
  1282. {
  1283. if (info.getAccessLevel() < 0)
  1284. @@ -461,8 +471,114 @@
  1285. }
  1286. }
  1287.  
  1288. +
  1289. +
  1290. public static LoginController getInstance()
  1291. {
  1292. return _instance;
  1293. }
  1294. +
  1295. + /**WORDPRESS PANEL*/
  1296. +
  1297. + /**pioneer
  1298. + * criacao de conta custom do wordpress
  1299. + * criado outra funcao para nao atrapalhar chamadas em outras classes
  1300. + * @param login
  1301. + * @param hashed
  1302. + * @param currentTime
  1303. + * @param wpUserId wordpress id
  1304. + * @return
  1305. + */
  1306. +
  1307. + public AccountInfo createAccount(String login, String hashed, long currentTime, int wpUserId)
  1308. + {
  1309. +
  1310. +
  1311. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1312. + {
  1313. + PreparedStatement ps = con.prepareStatement(INSERT_ACCOUNT);
  1314. + ps.setString(1, login);
  1315. + ps.setString(2, hashed);
  1316. + ps.setLong(3, System.currentTimeMillis());
  1317. + ps.setInt(4, 0);
  1318. + ps.setInt(5, wpUserId);
  1319. + ps.execute();
  1320. + ps.close();
  1321. + }
  1322. + catch (Exception e)
  1323. + {
  1324. + _log.log(Level.WARNING, "Exception while auto creating account for '" + login + "'!", e);
  1325. + return null;
  1326. + }
  1327. +
  1328. + // Generate a new Account.
  1329. + return new AccountInfo(login, hashed, 0, 1, wpUserId);
  1330. + }
  1331. +
  1332. +
  1333. + public boolean changePassword(String newPass, String accountName)
  1334. + {
  1335. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1336. + {
  1337. + PreparedStatement ps = con.prepareStatement(CHANGE_PASSWORD);
  1338. + ps.setString(1, newPass);
  1339. + ps.setString(2, accountName);
  1340. + ps.executeUpdate();
  1341. + }
  1342. + catch (Exception e)
  1343. + {
  1344. + _log.warning("Não foi possível alterar a senha de uma conta {"+accountName+"}. "+ e );
  1345. + return false;
  1346. + }
  1347. +
  1348. + return true;
  1349. + }
  1350. +
  1351. + public AccountInfo getAccount(String login)
  1352. + {
  1353. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1354. + {
  1355. + PreparedStatement ps = con.prepareStatement(USER_INFO_SELECT);
  1356. + ps.setString(1, login);
  1357. +
  1358. + try (ResultSet rs = ps.executeQuery())
  1359. + {
  1360. + if (rs.next())
  1361. + return new AccountInfo(login, rs.getString("password"), rs.getInt("access_level"), rs.getInt("lastServer"),rs.getInt("wp_user_id"));
  1362. + }
  1363. + //ps.executeUpdate();
  1364. + }
  1365. + catch (Exception e)
  1366. + {
  1367. + _log.severe("Falha ao obter o login do usuario #"+login+" do Wordpress. "+ e );
  1368. + }
  1369. + return null;
  1370. + }
  1371. +
  1372. + /**
  1373. + * @param wpUserId : ID do usuário do wordpress
  1374. + * @return Login da conta
  1375. + */
  1376. + public String getAccountLogin(int wpUserId)
  1377. +
  1378. + {
  1379. + try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1380. + {
  1381. + PreparedStatement ps = con.prepareStatement(SELECT_WP_ACCOUNT);
  1382. + ps.setInt(1, wpUserId);
  1383. +
  1384. + try (ResultSet rs = ps.executeQuery())
  1385. + {
  1386. + if (rs.next())
  1387. + return rs.getString("login");
  1388. + }
  1389. + ps.executeUpdate();
  1390. + }
  1391. + catch (Exception e)
  1392. + {
  1393. + _log.severe("Falha ao obter o login do usuário #"+wpUserId+" do Wordpress. "+ e );
  1394. + }
  1395. + return null;
  1396. + }
  1397. +
  1398. }
  1399. \ No newline at end of file
  1400. diff --git a/aCis_gameserver/java/net/sf/l2j/loginserver/LoginMessageConsumer.java b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginMessageConsumer.java
  1401. new file mode 100644
  1402. index 0000000..b7c2238
  1403. --- /dev/null
  1404. +++ b/aCis_gameserver/java/net/sf/l2j/loginserver/LoginMessageConsumer.java
  1405. @@ -0,0 +1,168 @@
  1406. +package net.sf.l2j.loginserver;
  1407. +
  1408. +import net.sf.l2j.commons.messagebroker.MBVariables;
  1409. +import net.sf.l2j.commons.messagebroker.MessageBrokerHandler;
  1410. +import net.sf.l2j.commons.messagebroker.AblyWebhook.*;
  1411. +
  1412. +import net.sf.l2j.Config;
  1413. +import net.sf.l2j.loginserver.model.AccountInfo;
  1414. +import net.sf.l2j.loginserver.model.GameServerInfo;
  1415. +import net.sf.l2j.loginserver.network.LoginClient;
  1416. +import net.sf.l2j.loginserver.network.serverpackets.LoginFail;
  1417. +import net.sf.l2j.loginserver.network.serverpackets.LoginFail.LoginFailReason;
  1418. +
  1419. +public class LoginMessageConsumer extends MessageBrokerHandler
  1420. +{
  1421. + protected LoginMessageConsumer()
  1422. + {
  1423. + super(MBVariables.LS_SERVER_ENDPOINT, MBVariables.LS_QUEUE_NAME, MBVariables.LS_VHOST);
  1424. + }
  1425. +
  1426. + @Override
  1427. + protected void handleMessage(Envelope envelope)
  1428. + {
  1429. + try
  1430. + {
  1431. + final CustomerData customer = GSON.fromJson(envelope.getMessage(), CustomerData.class);
  1432. + if (!validadeAuth(envelope.channel, customer))
  1433. + return;
  1434. +
  1435. + switch (envelope.getChannel())
  1436. + {
  1437. + case "customer.updated":
  1438. + updateAccount(customer);
  1439. + break;
  1440. +
  1441. + case "customer.created":
  1442. + createAccount(customer);
  1443. + break;
  1444. +
  1445. + default:
  1446. + LOGGER.warning("O canal '{"+envelope.getChannel()+"}' não possui um handler adequado no {"+getClass().getSimpleName()+"}.");
  1447. + break;
  1448. + }
  1449. + }
  1450. + catch (Exception e)
  1451. + {
  1452. + LOGGER.severe("Falha ao lidar com uma mensagem recebida pelo {"+getClass().getSimpleName()+"}. "+ e);
  1453. + }
  1454. + }
  1455. +
  1456. + /*
  1457. + * Código de LoginController
  1458. + */
  1459. + @Override
  1460. + protected void checkOnlineAccount(String username)
  1461. + {
  1462. + // Já está conectado no LoginServer
  1463. + final LoginClient client = LoginController.getInstance().getAuthedClient(username);
  1464. + if (client != null)
  1465. + {
  1466. + client.close(LoginFailReason.REASON_ACCOUNT_IN_USE);
  1467. + LoginController.getInstance().removeAuthedLoginClient(username);
  1468. + }
  1469. +
  1470. + // GameServer
  1471. + final GameServerInfo gsi = LoginController.getInstance().getAccountOnGameServer(username);
  1472. + if (gsi != null && gsi.isAuthed())
  1473. + gsi.getGameServerThread().kickPlayer(username);
  1474. + }
  1475. +
  1476. + /*
  1477. + * Altera a senha ou o accessLevel de uma conta existente
  1478. + */
  1479. + private void updateAccount(CustomerData customer)
  1480. + {
  1481. + if (!validateAccount(customer))
  1482. + return;
  1483. +
  1484. + // Se acontecer alguma alteração, podemos desconectar a conta depois
  1485. + boolean accountChanged = false;
  1486. +
  1487. + // Senha foi alterada
  1488. + if (customer.password_hash != null && !customer.password_hash.isEmpty())
  1489. + {
  1490. + final AccountInfo account = LoginController.getInstance().getAccount(customer.getUsername());
  1491. + final String newPass = fixPasswordHash(customer.password_hash);
  1492. +
  1493. + if (!account.checkPassHash(newPass))
  1494. + {
  1495. + if (!LoginController.getInstance().changePassword(newPass, customer.getUsername()))
  1496. + {
  1497. + LOGGER.warning("Não foi possível realizar a troca de senha da conta '{"+customer.getUsername()+"}' solicitada pelo Wordpress.");
  1498. + return;
  1499. + }
  1500. +
  1501. + if (Config.DEVELOPER)
  1502. + LOGGER.info("A alteração senha da conta '{"+customer.getUsername()+"}' solicitada pelo Wordpress foi realizada com sucesso.");
  1503. +
  1504. + accountChanged = true;
  1505. + }
  1506. + }
  1507. +
  1508. + // 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?
  1509. + // final int accessLevel = MBVariables.CREATE_ADMIN ? (customer.role.equals("administrator") ? 8 : 0) : 0;
  1510. + // if (account.getAccessLevel() >= 0 && account.getAccessLevel() != accessLevel)
  1511. + // {
  1512. + // AccountTable.getInstance().setAccountAccessLevel(customer.getUsername(), accessLevel);
  1513. + //
  1514. + // if (Config.DEVELOPER)
  1515. + // LOGGER.info("A alteração do acessLevel da conta '{}' solicitada pelo Wordpress foi realizada.", customer.getUsername());
  1516. + //
  1517. + // accountChanged = true;
  1518. + // }
  1519. +
  1520. + // Desconectar se estiver online
  1521. + if (accountChanged && MBVariables.LOGOUT_ACCOUNT_CHANGE)
  1522. + checkOnlineAccount(customer.getUsername());
  1523. + }
  1524. +
  1525. + /*
  1526. + * 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.
  1527. + */
  1528. + private static void createAccount(CustomerData customer)
  1529. + {
  1530. + if (LoginController.getInstance().getAccount(customer.getUsername()) != null)
  1531. + {
  1532. + LOGGER.warning("A conta '"+customer.getUsername()+"' enviada pelo Wordpress já existe no servidor.");
  1533. + return;
  1534. + }
  1535. +
  1536. + if (customer.password_hash == null || customer.password_hash.isEmpty())
  1537. + {
  1538. + LOGGER.warning("Falha ao criar a conta '"+customer.getUsername()+"' enviada pelo Wordpress. Ela não possui senha." );
  1539. + return;
  1540. + }
  1541. +
  1542. + final String pass = fixPasswordHash(customer.password_hash);
  1543. +// final int accessLevel = MBVariables.CREATE_ADMIN ? (customer.role.equals("administrator") ? 8 : 0) : 0;
  1544. +
  1545. + final AccountInfo account = LoginController.getInstance().createAccount(customer.getUsername(), pass, System.currentTimeMillis(), customer.getUserId());
  1546. + if (account == null)
  1547. + {
  1548. + LOGGER.warning("Falha ao criar a conta '{}' enviada pelo Wordpress");
  1549. + return;
  1550. + }
  1551. +
  1552. + if (Config.DEVELOPER)
  1553. + LOGGER.info("A conta '"+customer.getUsername()+"' enviada pelo Wordpress foi criada com sucesso.");
  1554. + }
  1555. +
  1556. + /*
  1557. + * O hash gerado pelo wp e o gerado pela acis tem essa pequena diferença
  1558. + */
  1559. + private static String fixPasswordHash(String wpPass)
  1560. + {
  1561. + return wpPass.replace("$2y$", "$2a$");
  1562. + }
  1563. +
  1564. + public static final LoginMessageConsumer getInstance()
  1565. + {
  1566. + return SingletonHolder._instance;
  1567. + }
  1568. +
  1569. + private static class SingletonHolder
  1570. + {
  1571. + protected static final LoginMessageConsumer _instance = new LoginMessageConsumer();
  1572. + }
  1573. +}
  1574. diff --git a/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java b/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java
  1575. index 9e2214c..ca6ce99 100644
  1576. --- a/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java
  1577. +++ b/aCis_gameserver/java/net/sf/l2j/loginserver/model/AccountInfo.java
  1578. @@ -8,8 +8,9 @@
  1579. private final String _passHash;
  1580. private final int _accessLevel;
  1581. private final int _lastServer;
  1582. + private final int _wpUserId;
  1583.  
  1584. - public AccountInfo(final String login, final String passHash, final int accessLevel, final int lastServer)
  1585. + public AccountInfo(final String login, final String passHash, final int accessLevel, final int lastServer,final int wpUserId)
  1586. {
  1587. Objects.requireNonNull(login, "login");
  1588. Objects.requireNonNull(passHash, "passHash");
  1589. @@ -24,6 +25,7 @@
  1590. _passHash = passHash;
  1591. _accessLevel = accessLevel;
  1592. _lastServer = lastServer;
  1593. + _wpUserId = wpUserId;
  1594. }
  1595.  
  1596. public boolean checkPassHash(final String passHash)
  1597. @@ -45,4 +47,9 @@
  1598. {
  1599. return _lastServer;
  1600. }
  1601. +
  1602. + public final int getWpUserId()
  1603. + {
  1604. + return _wpUserId;
  1605. + }
  1606. }
  1607. \ No newline at end of file
  1608.  
Add Comment
Please, Sign In to add comment