From 6563cf3a5395c8083a0cb41696fceafade852dd2 Mon Sep 17 00:00:00 2001 From: Mark Struchkov Date: Mon, 29 Apr 2019 12:12:38 +0300 Subject: [PATCH] =?UTF-8?q?=D0=91=D0=B5=D0=B7=20=D0=BF=D0=BE=D0=BD=D1=8F?= =?UTF-8?q?=D1=82=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 57 +++++++++++++ .../java/org/sadtech/vkbot/core/VkApi.java | 73 ++++++++++++++++ .../java/org/sadtech/vkbot/core/VkConfig.java | 79 ++++++++++++++++++ .../org/sadtech/vkbot/core/VkConnect.java | 58 +++++++++++++ .../org/sadtech/vkbot/core/VkInsertData.java | 40 +++++++++ .../core/distribution/CommentSubscriber.java | 26 ++++++ .../core/distribution/EventDistributor.java | 46 ++++++++++ .../core/distribution/EventSubscribe.java | 7 ++ .../core/distribution/MailSubscriber.java | 64 ++++++++++++++ .../core/distribution/TerminalSubscriber.java | 30 +++++++ .../vkbot/core/keyboard/ButtonKeyBoard.java | 74 +++++++++++++++++ .../vkbot/core/keyboard/ColorButton.java | 7 ++ .../sadtech/vkbot/core/keyboard/KeyBoard.java | 69 +++++++++++++++ .../vkbot/core/keyboard/KeyBoardService.java | 38 +++++++++ .../vkbot/core/keyboard/LineKeyBoard.java | 47 +++++++++++ .../vkbot/core/listener/EventListenerVk.java | 83 +++++++++++++++++++ .../vkbot/core/sender/MailSenderVk.java | 67 +++++++++++++++ .../vkbot/core/service/PersonServiceImpl.java | 74 +++++++++++++++++ .../service/distribution/CommentService.java | 10 +++ .../service/distribution/MailService.java | 8 ++ .../distribution/impl/CommentServiceImpl.java | 37 +++++++++ .../distribution/impl/MailServiceImpl.java | 70 ++++++++++++++++ 22 files changed, 1064 insertions(+) create mode 100644 pom.xml create mode 100644 src/main/java/org/sadtech/vkbot/core/VkApi.java create mode 100644 src/main/java/org/sadtech/vkbot/core/VkConfig.java create mode 100644 src/main/java/org/sadtech/vkbot/core/VkConnect.java create mode 100644 src/main/java/org/sadtech/vkbot/core/VkInsertData.java create mode 100644 src/main/java/org/sadtech/vkbot/core/distribution/CommentSubscriber.java create mode 100644 src/main/java/org/sadtech/vkbot/core/distribution/EventDistributor.java create mode 100644 src/main/java/org/sadtech/vkbot/core/distribution/EventSubscribe.java create mode 100644 src/main/java/org/sadtech/vkbot/core/distribution/MailSubscriber.java create mode 100644 src/main/java/org/sadtech/vkbot/core/distribution/TerminalSubscriber.java create mode 100644 src/main/java/org/sadtech/vkbot/core/keyboard/ButtonKeyBoard.java create mode 100644 src/main/java/org/sadtech/vkbot/core/keyboard/ColorButton.java create mode 100644 src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoard.java create mode 100644 src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoardService.java create mode 100644 src/main/java/org/sadtech/vkbot/core/keyboard/LineKeyBoard.java create mode 100644 src/main/java/org/sadtech/vkbot/core/listener/EventListenerVk.java create mode 100644 src/main/java/org/sadtech/vkbot/core/sender/MailSenderVk.java create mode 100644 src/main/java/org/sadtech/vkbot/core/service/PersonServiceImpl.java create mode 100644 src/main/java/org/sadtech/vkbot/core/service/distribution/CommentService.java create mode 100644 src/main/java/org/sadtech/vkbot/core/service/distribution/MailService.java create mode 100644 src/main/java/org/sadtech/vkbot/core/service/distribution/impl/CommentServiceImpl.java create mode 100644 src/main/java/org/sadtech/vkbot/core/service/distribution/impl/MailServiceImpl.java diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..6f8e7c3 --- /dev/null +++ b/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + org.sadtech.vkbot + vkbot-core + 1.0-SNAPSHOT + jar + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + + + 0.5.13-SNAPSHOT + 1.2.17 + + + + + com.vk.api + sdk + ${vksdk.ver} + + + + log4j + log4j + ${log4j.ver} + + + + org.sadtech.bot + bot-core + 0.4.3-SNAPSHOT + + + + + + Struchkov Mark + upagge@mail.ru + + + + \ No newline at end of file diff --git a/src/main/java/org/sadtech/vkbot/core/VkApi.java b/src/main/java/org/sadtech/vkbot/core/VkApi.java new file mode 100644 index 0000000..faf453c --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/VkApi.java @@ -0,0 +1,73 @@ +package org.sadtech.vkbot.core; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.vk.api.sdk.client.VkApiClient; +import com.vk.api.sdk.client.actors.GroupActor; +import com.vk.api.sdk.exceptions.ApiException; +import com.vk.api.sdk.exceptions.ClientException; +import com.vk.api.sdk.objects.users.UserMin; +import com.vk.api.sdk.objects.users.UserXtrCounters; +import com.vk.api.sdk.queries.users.UserField; +import org.apache.log4j.Logger; + +import java.util.List; + +public class VkApi { + + public static final Logger log = Logger.getLogger(String.valueOf(VkApi.class)); + + private VkApiClient vk; + private GroupActor actor; + + public VkApi(VkConnect vkConnect) { + vk = vkConnect.getVkApiClient(); + actor = vkConnect.getGroupActor(); + } + + public UserMin getUserMini(Integer id) { + UserMin userMin = null; + Gson gson = new Gson(); + try { + List temp = vk.users().get(actor).userIds(String.valueOf(id)).execute(); + JsonParser parser = new JsonParser(); + JsonObject object = parser.parse(temp.get(0).toString().substring(15)).getAsJsonObject(); + object.add("last_name", object.get("lastName")); + object.add("first_name", object.get("firstName")); + userMin = gson.fromJson(object, UserMin.class); + } catch (ApiException | ClientException e) { + log.error(e); + } + return userMin; + } + + public String getUserUniver(Integer id) { + List temp = null; + try { + temp = vk.users().get(actor).userIds(String.valueOf(id)).fields(UserField.UNIVERSITIES).execute(); + } catch (ApiException | ClientException e) { + log.error(e); + } + return temp != null ? temp.get(0).getUniversities().get(0).getName() : null; + } + + public String getUserCity(Integer id) { + List temp = null; + try { + temp = vk.users().get(actor).userIds(String.valueOf(id)).fields(UserField.CITY).execute(); + } catch (ApiException | ClientException e) { + log.error(e); + } + if (temp != null && checkCity(temp)) { + return temp.get(0).getCity().getTitle(); + } + return null; + } + + private boolean checkCity(List temp) { + log.info("Запрошен город пользователя: " + temp.get(0).getCity().getTitle()); + return temp.get(0).getCity() != null; + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/VkConfig.java b/src/main/java/org/sadtech/vkbot/core/VkConfig.java new file mode 100644 index 0000000..c0adbe5 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/VkConfig.java @@ -0,0 +1,79 @@ +package org.sadtech.vkbot.core; + +import java.util.Objects; + +public class VkConfig { + + private String groupToken; + private Integer groupId; + private String serviceToken; + private Integer appId; + private String groupSecretKey; + private String groupPublicKey; + + public String getGroupToken() { + return groupToken; + } + + public void setGroupToken(String groupToken) { + this.groupToken = groupToken; + } + + public Integer getGroupId() { + return groupId; + } + + public void setGroupId(Integer groupId) { + this.groupId = groupId; + } + + public String getServiceToken() { + return serviceToken; + } + + public void setServiceToken(String serviceToken) { + this.serviceToken = serviceToken; + } + + public Integer getAppId() { + return appId; + } + + public void setAppId(Integer appId) { + this.appId = appId; + } + + public String getGroupSecretKey() { + return groupSecretKey; + } + + public void setGroupSecretKey(String groupSecretKey) { + this.groupSecretKey = groupSecretKey; + } + + public String getGroupPublicKey() { + return groupPublicKey; + } + + public void setGroupPublicKey(String groupPublicKey) { + this.groupPublicKey = groupPublicKey; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + VkConfig vkConfig = (VkConfig) o; + return Objects.equals(groupToken, vkConfig.groupToken) && + Objects.equals(groupId, vkConfig.groupId) && + Objects.equals(serviceToken, vkConfig.serviceToken) && + Objects.equals(appId, vkConfig.appId) && + Objects.equals(groupSecretKey, vkConfig.groupSecretKey) && + Objects.equals(groupPublicKey, vkConfig.groupPublicKey); + } + + @Override + public int hashCode() { + return Objects.hash(groupToken, groupId, serviceToken, appId, groupSecretKey, groupPublicKey); + } +} diff --git a/src/main/java/org/sadtech/vkbot/core/VkConnect.java b/src/main/java/org/sadtech/vkbot/core/VkConnect.java new file mode 100644 index 0000000..c10e7bd --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/VkConnect.java @@ -0,0 +1,58 @@ +package org.sadtech.vkbot.core; + +import com.vk.api.sdk.client.VkApiClient; +import com.vk.api.sdk.client.actors.GroupActor; +import com.vk.api.sdk.client.actors.ServiceActor; +import com.vk.api.sdk.httpclient.HttpTransportClient; + +public class VkConnect { + + private VkConfig vkConfig; + + private VkApiClient vkApiClient; + private GroupActor groupActor; + private ServiceActor serviceActor; + + public VkConnect(VkConfig vkConfig) { + this.vkConfig = vkConfig; + } + + public VkApiClient getVkApiClient() { + if (vkApiClient != null) { + return vkApiClient; + } else { + initVkApiClient(); + return vkApiClient; + } + } + + public GroupActor getGroupActor() { + if (groupActor != null) { + return groupActor; + } else { + initGroupActor(); + return groupActor; + } + } + + public ServiceActor getServiceActor() { + if (serviceActor != null) { + return serviceActor; + } else { + initServiceActor(); + return serviceActor; + } + } + + private void initVkApiClient() { + vkApiClient = new VkApiClient(HttpTransportClient.getInstance()); + } + + private void initGroupActor() { + groupActor = new GroupActor(vkConfig.getGroupId(), vkConfig.getGroupToken()); + } + + private void initServiceActor() { + serviceActor = new ServiceActor(vkConfig.getAppId(), vkConfig.getServiceToken()); + } +} diff --git a/src/main/java/org/sadtech/vkbot/core/VkInsertData.java b/src/main/java/org/sadtech/vkbot/core/VkInsertData.java new file mode 100644 index 0000000..327ae22 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/VkInsertData.java @@ -0,0 +1,40 @@ +package org.sadtech.vkbot.core; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class VkInsertData { + + private VkApi vkApi; + + public VkInsertData(VkConnect vkConnect) { + this.vkApi = new VkApi(vkConnect); + } + + public String insertWords(String message, Integer idUser) { + Pattern pattern = Pattern.compile("%(\\w+)%"); + Matcher m = pattern.matcher(message); + StringBuffer result = new StringBuffer(); + while (m.find()) { + m.appendReplacement(result, insert(m.group(0), idUser)); + } + m.appendTail(result); + return result.toString(); + } + + private String insert(String key, Integer userId) { + String string = ""; + switch (key) { + case "%firstname%": + string = vkApi.getUserMini(userId).getFirstName(); + break; + case "%lastname%": + string = vkApi.getUserMini(userId).getLastName(); + break; + default: + break; + } + return string; + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/distribution/CommentSubscriber.java b/src/main/java/org/sadtech/vkbot/core/distribution/CommentSubscriber.java new file mode 100644 index 0000000..06a8b53 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/distribution/CommentSubscriber.java @@ -0,0 +1,26 @@ +package org.sadtech.vkbot.core.distribution; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.vk.api.sdk.objects.wall.WallComment; +import org.apache.log4j.Logger; +import org.sadtech.vkbot.core.service.distribution.CommentService; + +public class CommentSubscriber implements EventSubscribe { + + public static final Logger log = Logger.getLogger(CommentSubscriber.class); + + private CommentService commentService; + + public CommentSubscriber(CommentService commentService) { + this.commentService = commentService; + } + + @Override + public void update(JsonObject object) { + Gson gson = new Gson(); + WallComment wallComment = gson.fromJson(object, WallComment.class); + log.info(wallComment); + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/distribution/EventDistributor.java b/src/main/java/org/sadtech/vkbot/core/distribution/EventDistributor.java new file mode 100644 index 0000000..3d1c4d9 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/distribution/EventDistributor.java @@ -0,0 +1,46 @@ +package org.sadtech.vkbot.core.distribution; + +import com.google.gson.JsonObject; +import org.apache.log4j.Logger; +import org.sadtech.bot.core.service.RawEventService; + +import java.util.HashMap; +import java.util.Map; + +public class EventDistributor implements Runnable { + + public static final Logger log = Logger.getLogger(EventDistributor.class); + + private RawEventService rawEventService; + private Map eventDistributionMap = new HashMap<>(); + + public EventDistributor(RawEventService rawEventService) { + this.rawEventService = rawEventService; + } + + public void update() { + while (true) { + try { + if (rawEventService.getJsonObjects().peek() != null) { + JsonObject event = rawEventService.getJsonObjects().poll(); + log.info("Главный дистрибьютор отправил событие дальше"); + if (eventDistributionMap.containsKey(event.get("type").getAsString())) { + eventDistributionMap.get(event.get("type").getAsString()).update(event.getAsJsonObject("object")); + } + } + } catch (Exception e) { + log.error(e.getStackTrace()); + break; + } + } + } + + public void setEventDistributionMap(String key, EventSubscribe eventSubscribe) { + this.eventDistributionMap.put(key, eventSubscribe); + } + + @Override + public void run() { + update(); + } +} diff --git a/src/main/java/org/sadtech/vkbot/core/distribution/EventSubscribe.java b/src/main/java/org/sadtech/vkbot/core/distribution/EventSubscribe.java new file mode 100644 index 0000000..bd8dead --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/distribution/EventSubscribe.java @@ -0,0 +1,7 @@ +package org.sadtech.vkbot.core.distribution; + +public interface EventSubscribe { + + void update(T object); + +} diff --git a/src/main/java/org/sadtech/vkbot/core/distribution/MailSubscriber.java b/src/main/java/org/sadtech/vkbot/core/distribution/MailSubscriber.java new file mode 100644 index 0000000..7054895 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/distribution/MailSubscriber.java @@ -0,0 +1,64 @@ +package org.sadtech.vkbot.core.distribution; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.vk.api.sdk.objects.messages.Message; +import org.apache.log4j.Logger; +import org.sadtech.bot.core.domain.Mail; +import org.sadtech.vkbot.core.service.distribution.MailService; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class MailSubscriber implements EventSubscribe { + + public static final Logger log = Logger.getLogger(MailSubscriber.class); + + private MailService mailService; + private Set admins = new HashSet<>(); + private Map> eventDistributionMap = new HashMap<>(); + + public MailSubscriber(MailService mailService) { + this.mailService = mailService; + } + + public void setAdmins(Set admins) { + this.admins = admins; + } + + public Set getAdmins() { + return admins; + } + + @Override + public void update(JsonObject object) { + log.info("Дистрибьютор получил событие - сообщение"); + Gson gson = new Gson(); + Message userMessage = gson.fromJson(object, Message.class); + if (userMessage.getPeerId() > 2000000000) { + if (eventDistributionMap.containsKey("chat")) { + eventDistributionMap.get("chat").update(userMessage); + } + } else { + if (admins.contains(userMessage.getUserId()) && eventDistributionMap.containsKey("terminal")) { + log.info("Сообщение отправлено в репозиторий команд"); + eventDistributionMap.get("terminal").update(userMessage); + } else { + log.info("Сообщение отправленно на добавление в репозиторий"); + mailService.add(createMaail(userMessage)); + } + } + } + + private Mail createMaail(Message message) { + Mail mail = new Mail(); + mail.setBody(message.getBody()); + mail.setDate(message.getDate()); + mail.setId(message.getId()); + mail.setPeerId(message.getPeerId()); + return mail; + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/distribution/TerminalSubscriber.java b/src/main/java/org/sadtech/vkbot/core/distribution/TerminalSubscriber.java new file mode 100644 index 0000000..ad97fa9 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/distribution/TerminalSubscriber.java @@ -0,0 +1,30 @@ +package org.sadtech.vkbot.core.distribution; + +import com.vk.api.sdk.objects.messages.Message; +import org.apache.log4j.Logger; +import org.sadtech.vkbot.core.service.distribution.MailService; + +public class TerminalSubscriber implements EventSubscribe { + + public static final Logger log = Logger.getLogger(TerminalSubscriber.class); + + private MailService mailService; + + public TerminalSubscriber(MailSubscriber mailSubscriber, MailService mailService) { + this.mailService = mailService; + } + + public MailService getMailService() { + return mailService; + } + + public void setMailService(MailService mailService) { + this.mailService = mailService; + } + + @Override + public void update(Message object) { + log.info("Сообщение отправленно на добавление в репозиторий команд"); + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/keyboard/ButtonKeyBoard.java b/src/main/java/org/sadtech/vkbot/core/keyboard/ButtonKeyBoard.java new file mode 100644 index 0000000..fa9612f --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/keyboard/ButtonKeyBoard.java @@ -0,0 +1,74 @@ +package org.sadtech.vkbot.core.keyboard; + +import com.google.gson.JsonObject; + +public class ButtonKeyBoard { + + private String type = "text"; + private String payload; + private String label; + private ColorButton color = ColorButton.PRIMARY; + + public ButtonKeyBoard() { + + } + + public ButtonKeyBoard(String type, String payload, String label, ColorButton color) { + this.type = type; + this.payload = payload; + this.label = label; + this.color = color; + } + + public JsonObject getButton() { + JsonObject newButton = new JsonObject(); + newButton.addProperty("color", color.toString().toLowerCase()); + newButton.add("action", generateAction()); + return newButton; + } + + private JsonObject generateAction() { + JsonObject action = new JsonObject(); + action.addProperty("type", type); + action.addProperty("payload", payload); + action.addProperty("label", label); + return action; + } + + public static Builder builder() { + return new ButtonKeyBoard().new Builder(); + } + + public class Builder { + + private Builder() { + + } + + public Builder setColor(ColorButton color) { + ButtonKeyBoard.this.color = color; + return this; + } + + public Builder setLabel(String label) { + ButtonKeyBoard.this.label = label; + return this; + } + + public Builder setPayload(String payload) { + ButtonKeyBoard.this.payload = payload; + return this; + } + + public Builder setType(String type) { + ButtonKeyBoard.this.type = type; + return this; + } + + public ButtonKeyBoard build() { + return ButtonKeyBoard.this; + } + + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/keyboard/ColorButton.java b/src/main/java/org/sadtech/vkbot/core/keyboard/ColorButton.java new file mode 100644 index 0000000..6eb856b --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/keyboard/ColorButton.java @@ -0,0 +1,7 @@ +package org.sadtech.vkbot.core.keyboard; + +public enum ColorButton { + + PRIMARY, DEFAULT, NEGATIVE, POSITIVE + +} diff --git a/src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoard.java b/src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoard.java new file mode 100644 index 0000000..08cdf86 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoard.java @@ -0,0 +1,69 @@ +package org.sadtech.vkbot.core.keyboard; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; + +public class KeyBoard { + + private List lineKeyBoards = new ArrayList<>(); + private boolean oneTime; + + public KeyBoard() { + + } + + public KeyBoard(List lineKeyBoards, boolean oneTime) { + this.lineKeyBoards = lineKeyBoards; + this.oneTime = oneTime; + } + + public void setOneTime(boolean oneTime) { + this.oneTime = oneTime; + } + + public JsonObject getKeyboard() { + JsonObject keyboard = new JsonObject(); + keyboard.addProperty("one_time", oneTime); + + JsonArray menuLine = new JsonArray(); + for (LineKeyBoard lineKeyboard : lineKeyBoards) { + menuLine.add(lineKeyboard.getLine()); + } + + keyboard.add("buttons", menuLine); + return keyboard; + } + + public void addLine(LineKeyBoard lineKeyBoard) { + lineKeyBoards.add(lineKeyBoard); + } + + public static Builder builder() { + return new KeyBoard().new Builder(); + } + + public class Builder { + + private Builder() { + + } + + public Builder setLineKeyBoard(LineKeyBoard lineKeyBoard) { + KeyBoard.this.lineKeyBoards.add(lineKeyBoard); + return this; + } + + public Builder setOneTime(boolean oneTime) { + KeyBoard.this.oneTime = oneTime; + return this; + } + + public KeyBoard build() { + return KeyBoard.this; + } + + } +} diff --git a/src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoardService.java b/src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoardService.java new file mode 100644 index 0000000..910522e --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/keyboard/KeyBoardService.java @@ -0,0 +1,38 @@ +package org.sadtech.vkbot.core.keyboard; + +import java.util.List; + +public class KeyBoardService { + + private KeyBoardService() { + throw new IllegalStateException(); + } + + public static KeyBoard keyBoardYesNo() { + ButtonKeyBoard yesButton = ButtonKeyBoard.builder().setColor(ColorButton.POSITIVE).setLabel("Да").setPayload("{\"button\": \"yes\"}").build(); + ButtonKeyBoard noButton = ButtonKeyBoard.builder().setColor(ColorButton.NEGATIVE).setLabel("Нет").setPayload("{\"button\": \"no\"}").build(); + LineKeyBoard lineKeyBoard = LineKeyBoard.builder().setButtonKeyBoard(yesButton).setButtonKeyBoard(noButton).build(); + KeyBoard keyBoard = KeyBoard.builder().setLineKeyBoard(lineKeyBoard).build(); + keyBoard.setOneTime(true); + return keyBoard; + } + + public static KeyBoard verticalMenuString(List labelButtons) { + KeyBoard keyBoard = new KeyBoard(); + for (String labelButton : labelButtons) { + ButtonKeyBoard buttonKeyBoard = ButtonKeyBoard.builder().setLabel(labelButton).setType("text").setPayload("{\"button\": \"" + labelButton + "\"}").build(); + keyBoard.addLine(LineKeyBoard.builder().setButtonKeyBoard(buttonKeyBoard).build()); + } + keyBoard.setOneTime(true); + return keyBoard; + } + + public static KeyBoard verticalMenuButton(List buttonKeyBoards) { + KeyBoard keyBoard = new KeyBoard(); + for (ButtonKeyBoard buttonKeyBoard : buttonKeyBoards) { + keyBoard.addLine(LineKeyBoard.builder().setButtonKeyBoard(buttonKeyBoard).build()); + } + keyBoard.setOneTime(true); + return keyBoard; + } +} diff --git a/src/main/java/org/sadtech/vkbot/core/keyboard/LineKeyBoard.java b/src/main/java/org/sadtech/vkbot/core/keyboard/LineKeyBoard.java new file mode 100644 index 0000000..6b28849 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/keyboard/LineKeyBoard.java @@ -0,0 +1,47 @@ +package org.sadtech.vkbot.core.keyboard; + +import com.google.gson.JsonArray; + +import java.util.ArrayList; +import java.util.List; + +public class LineKeyBoard { + + private List buttonKeyBoards = new ArrayList<>(); + + public LineKeyBoard() { + + } + + public LineKeyBoard(List buttonKeyBoards) { + this.buttonKeyBoards = buttonKeyBoards; + } + + public JsonArray getLine() { + JsonArray line = new JsonArray(); + for (ButtonKeyBoard buttonKeyBoard : buttonKeyBoards) { + line.add(buttonKeyBoard.getButton()); + } + return line; + } + + public static Builder builder() { + return new LineKeyBoard().new Builder(); + } + + public class Builder { + + private Builder() { + + } + + public Builder setButtonKeyBoard(ButtonKeyBoard buttonKeyBoard) { + LineKeyBoard.this.buttonKeyBoards.add(buttonKeyBoard); + return this; + } + + public LineKeyBoard build() { + return LineKeyBoard.this; + } + } +} diff --git a/src/main/java/org/sadtech/vkbot/core/listener/EventListenerVk.java b/src/main/java/org/sadtech/vkbot/core/listener/EventListenerVk.java new file mode 100644 index 0000000..25ed220 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/listener/EventListenerVk.java @@ -0,0 +1,83 @@ +package org.sadtech.vkbot.core.listener; + +import com.google.gson.JsonObject; +import com.vk.api.sdk.callback.longpoll.responses.GetLongPollEventsResponse; +import com.vk.api.sdk.client.VkApiClient; +import com.vk.api.sdk.client.actors.GroupActor; +import com.vk.api.sdk.exceptions.ApiException; +import com.vk.api.sdk.exceptions.ClientException; +import com.vk.api.sdk.exceptions.LongPollServerKeyExpiredException; +import com.vk.api.sdk.objects.groups.responses.GetLongPollServerResponse; +import org.apache.log4j.Logger; +import org.sadtech.bot.core.repository.impl.EventRepositoryQueue; +import org.sadtech.bot.core.service.RawEventService; +import org.sadtech.bot.core.service.impl.RawEventServiceImpl; +import org.sadtech.vkbot.core.VkConnect; + +public class EventListenerVk implements Runnable { + + public static final Logger log = Logger.getLogger(EventListenerVk.class); + + private VkApiClient vk; + private GroupActor actor; + + private static final Integer DEFAULT_WAIT_TIME = 25; + + private RawEventService rawEventService; + + public EventListenerVk(VkConnect vkConnect) { + vk = vkConnect.getVkApiClient(); + actor = vkConnect.getGroupActor(); + rawEventService = new RawEventServiceImpl(new EventRepositoryQueue()); + } + + public EventListenerVk(VkConnect vkConnect, RawEventService rawEventService) { + this.vk = vkConnect.getVkApiClient(); + this.actor = vkConnect.getGroupActor(); + this.rawEventService = rawEventService; + } + + public RawEventService getRawEventService() { + return rawEventService; + } + + public void listen() throws ClientException, ApiException { + GetLongPollServerResponse longPollServer = getLongPollServer(); + int lastTimeStamp = longPollServer.getTs(); + while (true) { + try { + GetLongPollEventsResponse eventsResponse = vk.longPoll().getEvents(longPollServer.getServer(), longPollServer.getKey(), lastTimeStamp).waitTime(DEFAULT_WAIT_TIME).execute(); + for (JsonObject jsonObject : eventsResponse.getUpdates()) { + log.info("Новое событие от LongPoll\n" + jsonObject); + rawEventService.add(jsonObject); + } + lastTimeStamp = eventsResponse.getTs(); + } catch (LongPollServerKeyExpiredException e) { + log.error(e.getStackTrace()); + longPollServer = getLongPollServer(); + } catch (Exception e) { + log.error(e.getStackTrace()); + break; + } + } + } + + private GetLongPollServerResponse getLongPollServer() throws ClientException, ApiException { + log.info("LongPoll сервер инициализирован"); + if (actor != null) { + return vk.groups().getLongPollServer(actor).execute(); + } else { + throw new NullPointerException("Group actor"); + } + } + + @Override + public void run() { + try { + listen(); + } catch (ClientException | ApiException e) { + log.error(e); + } + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/sender/MailSenderVk.java b/src/main/java/org/sadtech/vkbot/core/sender/MailSenderVk.java new file mode 100644 index 0000000..4326d5b --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/sender/MailSenderVk.java @@ -0,0 +1,67 @@ +package org.sadtech.vkbot.core.sender; + +import com.vk.api.sdk.client.VkApiClient; +import com.vk.api.sdk.client.actors.GroupActor; +import com.vk.api.sdk.exceptions.ApiException; +import com.vk.api.sdk.exceptions.ClientException; +import com.vk.api.sdk.queries.messages.MessagesSendQuery; +import org.apache.log4j.Logger; +import org.sadtech.bot.core.domain.BoxAnswer; +import org.sadtech.bot.core.sender.Sent; +import org.sadtech.vkbot.core.VkConnect; +import org.sadtech.vkbot.core.VkInsertData; + +public class MailSenderVk implements Sent { + + public static final Logger log = Logger.getLogger(MailSenderVk.class); + + private VkApiClient vkApiClient; + private GroupActor groupActor; + + private VkInsertData vkInsertData; + + public MailSenderVk(VkConnect vkConnect) { + this.vkApiClient = vkConnect.getVkApiClient(); + this.groupActor = vkConnect.getGroupActor(); + this.vkInsertData = new VkInsertData(vkConnect); + } + + @Override + public void send(Integer idPerson, String message) { + sendMessage(vkApiClient.messages().send(groupActor).peerId(idPerson).message(message)); + } + + @Override + public void send(Integer idPerson, BoxAnswer boxAnswer) { + MessagesSendQuery messagesSendQuery = createMessage(boxAnswer, idPerson); + sendMessage(messagesSendQuery); + } + + private MessagesSendQuery createMessage(BoxAnswer boxAnswer, Integer peerId) { + MessagesSendQuery messages = vkApiClient.messages().send(groupActor).peerId(peerId).message(vkInsertData.insertWords(boxAnswer.getMessage(), peerId)); + if (boxAnswer.getKeyboard() != null) { + messages.keyboard(boxAnswer.getKeyboard()); + } else { + messages.keyboard("{\"buttons\":[],\"one_time\":true}"); + } + if (boxAnswer.getLat() != null && boxAnswer.getaLong() != null) { + messages.lat(boxAnswer.getLat()).lng(boxAnswer.getaLong()); + } + if (boxAnswer.getStickerId() != null) { + try { + vkApiClient.messages().send(groupActor).peerId(peerId).stickerId(boxAnswer.getStickerId()).execute(); + } catch (ApiException | ClientException e) { + log.error(e); + } + } + return messages; + } + + private void sendMessage(MessagesSendQuery messages) { + try { + messages.execute(); + } catch (ApiException | ClientException e) { + log.error(e); + } + } +} diff --git a/src/main/java/org/sadtech/vkbot/core/service/PersonServiceImpl.java b/src/main/java/org/sadtech/vkbot/core/service/PersonServiceImpl.java new file mode 100644 index 0000000..5c950ef --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/service/PersonServiceImpl.java @@ -0,0 +1,74 @@ +package org.sadtech.vkbot.core.service; + +import com.vk.api.sdk.objects.users.User; +import com.vk.api.sdk.objects.users.UserMin; +import org.apache.log4j.Logger; +import org.sadtech.bot.core.domain.Person; +import org.sadtech.bot.core.repository.PersonRepository; +import org.sadtech.bot.core.repository.impl.PersonRepositoryMap; +import org.sadtech.bot.core.service.PersonService; +import org.sadtech.vkbot.core.VkApi; +import org.sadtech.vkbot.core.VkConnect; + +public class PersonServiceImpl implements PersonService { + + public static final Logger log = Logger.getLogger(PersonServiceImpl.class); + + private PersonRepository personRepository; + private VkApi vkApi; + + public PersonServiceImpl(VkConnect vkConnect) { + this.personRepository = new PersonRepositoryMap(); + vkApi = new VkApi(vkConnect); + } + + public PersonServiceImpl(PersonRepository personRepository, VkConnect vkConnect) { + this.personRepository = personRepository; + vkApi = new VkApi(vkConnect); + } + + public void add(User user) { + Person person = new Person(); + person.setId(user.getId()); + person.setLastName(user.getLastName()); + person.setFirstName(user.getFirstName()); + personRepository.add(person); + log.info("Пользователь добавлен в репозиторий"); + } + + @Override + public void add(Person person) { + personRepository.add(person); + log.info("Пользователь добавлен в репозиторий"); + } + + public void add(UserMin userMin) { + Person person = new Person(); + person.setId(userMin.getId()); + person.setFirstName(userMin.getFirstName()); + person.setLastName(userMin.getLastName()); + personRepository.add(person); + } + + @Override + public Person get(Integer id) { + return personRepository.get(id); + } + + @Override + public boolean checkPerson(Integer idPerson) { + log.info("Проверка наличия пользователя в репозитории"); + return get(idPerson) != null; + } + + @Override + public Person createPerson(Integer userId) { + Person person = new Person(); + UserMin userMin = vkApi.getUserMini(userId); + person.setId(userMin.getId()); + person.setLastName(userMin.getLastName()); + person.setFirstName(userMin.getFirstName()); + return person; + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/service/distribution/CommentService.java b/src/main/java/org/sadtech/vkbot/core/service/distribution/CommentService.java new file mode 100644 index 0000000..6830e21 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/service/distribution/CommentService.java @@ -0,0 +1,10 @@ +package org.sadtech.vkbot.core.service.distribution; + +import org.sadtech.bot.core.domain.Comment; +import org.sadtech.bot.core.service.EventService; + +//@TODO: Дописать класс +public interface CommentService extends EventService { + + +} diff --git a/src/main/java/org/sadtech/vkbot/core/service/distribution/MailService.java b/src/main/java/org/sadtech/vkbot/core/service/distribution/MailService.java new file mode 100644 index 0000000..5d1bbe7 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/service/distribution/MailService.java @@ -0,0 +1,8 @@ +package org.sadtech.vkbot.core.service.distribution; + +import org.sadtech.bot.core.domain.Mail; +import org.sadtech.bot.core.service.EventService; + +public interface MailService extends EventService { + +} diff --git a/src/main/java/org/sadtech/vkbot/core/service/distribution/impl/CommentServiceImpl.java b/src/main/java/org/sadtech/vkbot/core/service/distribution/impl/CommentServiceImpl.java new file mode 100644 index 0000000..8641c94 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/service/distribution/impl/CommentServiceImpl.java @@ -0,0 +1,37 @@ +package org.sadtech.vkbot.core.service.distribution.impl; + +import org.sadtech.bot.core.domain.Comment; +import org.sadtech.bot.core.repository.CommentRepository; +import org.sadtech.vkbot.core.service.distribution.CommentService; + +import java.util.List; + +public class CommentServiceImpl implements CommentService { + + private CommentRepository commentRepository; + + public CommentServiceImpl(CommentRepository commentRepository) { + this.commentRepository = commentRepository; + } + + @Override + public void add(Comment comment) { + commentRepository.add(comment); + } + + @Override + public List getEvent(Integer timeFrom, Integer timeTo) { + return null; + } + + @Override + public List getFirstEventByTime(Integer timeFrom, Integer timeTo) { + return null; + } + + @Override + public List getLastEventByTime(Integer timeFrom, Integer timeTo) { + return null; + } + +} diff --git a/src/main/java/org/sadtech/vkbot/core/service/distribution/impl/MailServiceImpl.java b/src/main/java/org/sadtech/vkbot/core/service/distribution/impl/MailServiceImpl.java new file mode 100644 index 0000000..6fc8dc8 --- /dev/null +++ b/src/main/java/org/sadtech/vkbot/core/service/distribution/impl/MailServiceImpl.java @@ -0,0 +1,70 @@ +package org.sadtech.vkbot.core.service.distribution.impl; + +import org.apache.log4j.Logger; +import org.sadtech.bot.core.domain.Mail; +import org.sadtech.bot.core.repository.MailRepository; +import org.sadtech.bot.core.repository.impl.MailRepositoryList; +import org.sadtech.vkbot.core.service.distribution.MailService; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class MailServiceImpl implements MailService { + + public static final Logger log = Logger.getLogger(MailServiceImpl.class); + + private MailRepository mailRepository; + + public MailServiceImpl() { + this.mailRepository = new MailRepositoryList(); + } + + public MailServiceImpl(MailRepository mailRepository) { + this.mailRepository = mailRepository; + } + + @Override + public void add(Mail mail) { + mailRepository.add(mail); + log.info("Сообщение добавлено в репозиторий"); + log.info(mail); + } + + @Override + public List getFirstEventByTime(Integer timeFrom, Integer timeTo) { + log.info("Запрошены сообщения " + timeFrom + "-" + timeTo); + List mails = mailRepository.getMailByTime(timeFrom, timeTo); + Set people = new HashSet<>(); + List returnMails = new ArrayList<>(); + for (int i = mails.size() - 1; i >= 0; i--) { + if (!people.contains(mails.get(i).getPeerId())) { + returnMails.add(mails.get(i)); + people.add(mails.get(i).getPeerId()); + } + } + return returnMails; + } + + @Override + public List getLastEventByTime(Integer timeFrom, Integer timeTo) { + List mails = mailRepository.getMailByTime(timeFrom, timeTo); + Set people = new HashSet<>(); + List returnMails = new ArrayList<>(); + for (Mail mail : mails) { + if (!people.contains(mail.getPeerId())) { + returnMails.add(mail); + people.add(mail.getPeerId()); + } + } + return returnMails; + } + + @Override + public List getEvent(Integer timeFrom, Integer timeTo) { + log.info("Запрос на получение сообщений в интервале от " + timeFrom + " до " + timeTo); + return mailRepository.getMailByTime(timeFrom, timeTo); + } + +}