Merge branch 'release/release-0.2.1'

This commit is contained in:
Mark Struchkov 2019-06-15 15:32:45 +03:00
commit 1be423c7c2
24 changed files with 783 additions and 325 deletions

View File

@ -6,7 +6,7 @@
<groupId>org.sadtech.vkbot</groupId>
<artifactId>vkbot-core</artifactId>
<version>0.2.0-RELEASE</version>
<version>0.2.1-RELEASE</version>
<packaging>jar</packaging>
<build>
@ -23,8 +23,9 @@
</build>
<properties>
<bot.core.ver>0.6.0-RELEASE</bot.core.ver>
<vksdk.ver>0.5.13-SNAPSHOT</vksdk.ver>
<bot.core.ver>0.6.2-RELEASE</bot.core.ver>
<vksdk.ver>0.5.13-FORK</vksdk.ver>
<log4j.ver>1.2.17</log4j.ver>
</properties>

View File

@ -1,79 +0,0 @@
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);
}
}

View File

@ -0,0 +1,75 @@
package org.sadtech.vkbot.core.config;
import org.sadtech.vkbot.core.exception.ConfigException;
import java.util.Objects;
import java.util.Optional;
public class VkConfig {
private VkConfigGroup configGroup;
private VkConfigUser configUser;
private VkConfigService configService;
public VkConfigGroup getConfigGroup() {
return Optional.ofNullable(configGroup)
.orElseThrow(() -> new ConfigException("Конфигурация сервиса для группы найдена"));
}
public VkConfigUser getConfigUser() {
return Optional.ofNullable(configUser)
.orElseThrow(() -> new ConfigException("Конфигурация для пользователя не найдена"));
}
public VkConfigService getConfigService() {
return Optional.ofNullable(configService)
.orElseThrow(() -> new ConfigException("Конфигурация сервиса не найдена"));
}
public static Builder builder() {
return new VkConfig().new Builder();
}
public class Builder {
private Builder() {
}
public Builder configGroup(VkConfigGroup configGroup) {
VkConfig.this.configGroup = configGroup;
return this;
}
public Builder configUser(VkConfigUser configUser) {
VkConfig.this.configUser = configUser;
return this;
}
public Builder configService(VkConfigService configService) {
VkConfig.this.configService = configService;
return this;
}
public VkConfig build() {
return VkConfig.this;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VkConfig)) return false;
VkConfig vkConfig = (VkConfig) o;
return Objects.equals(configGroup, vkConfig.configGroup) &&
Objects.equals(configUser, vkConfig.configUser) &&
Objects.equals(configService, vkConfig.configService);
}
@Override
public int hashCode() {
return Objects.hash(configGroup, configUser, configService);
}
}

View File

@ -0,0 +1,56 @@
package org.sadtech.vkbot.core.config;
import java.util.Objects;
public class VkConfigGroup {
private String groupToken;
private Integer groupId;
public String getGroupToken() {
return groupToken;
}
public Integer getGroupId() {
return groupId;
}
public static Builder builder() {
return new VkConfigGroup().new Builder();
}
public class Builder {
private Builder() {
}
public Builder groupId(Integer groupId) {
VkConfigGroup.this.groupId = groupId;
return this;
}
public Builder groupToken(String groupToken) {
VkConfigGroup.this.groupToken = groupToken;
return this;
}
public VkConfigGroup build() {
return VkConfigGroup.this;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VkConfigGroup)) return false;
VkConfigGroup that = (VkConfigGroup) o;
return Objects.equals(groupToken, that.groupToken) &&
Objects.equals(groupId, that.groupId);
}
@Override
public int hashCode() {
return Objects.hash(groupToken, groupId);
}
}

View File

@ -0,0 +1,56 @@
package org.sadtech.vkbot.core.config;
import java.util.Objects;
public class VkConfigService {
private String serviceToken;
private Integer appId;
public String getServiceToken() {
return serviceToken;
}
public Integer getAppId() {
return appId;
}
public static Builder builder() {
return new VkConfigService().new Builder();
}
public class Builder {
private Builder() {
}
public Builder serviceToken(String serviceToken) {
VkConfigService.this.serviceToken = serviceToken;
return this;
}
public Builder appId(Integer appId) {
VkConfigService.this.appId = appId;
return this;
}
public VkConfigService build() {
return VkConfigService.this;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VkConfigService)) return false;
VkConfigService that = (VkConfigService) o;
return Objects.equals(serviceToken, that.serviceToken) &&
Objects.equals(appId, that.appId);
}
@Override
public int hashCode() {
return Objects.hash(serviceToken, appId);
}
}

View File

@ -0,0 +1,61 @@
package org.sadtech.vkbot.core.config;
import java.util.Objects;
public class VkConfigUser {
private Integer userId;
private String token;
private VkConfigUser() {
}
public Integer getUserId() {
return userId;
}
public String getToken() {
return token;
}
public static Builder builder() {
return new VkConfigUser().new Builder();
}
public class Builder {
private Builder() {
}
public Builder userId(Integer userId) {
VkConfigUser.this.userId = userId;
return this;
}
public Builder token(String token) {
VkConfigUser.this.token = token;
return this;
}
public VkConfigUser build() {
return VkConfigUser.this;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VkConfigUser)) return false;
VkConfigUser that = (VkConfigUser) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(token, that.token);
}
@Override
public int hashCode() {
return Objects.hash(userId, token);
}
}

View File

@ -1,8 +1,9 @@
package org.sadtech.vkbot.core;
package org.sadtech.vkbot.core.config;
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.client.actors.UserActor;
import com.vk.api.sdk.httpclient.HttpTransportClient;
public class VkConnect {
@ -12,6 +13,7 @@ public class VkConnect {
private VkApiClient vkApiClient;
private GroupActor groupActor;
private ServiceActor serviceActor;
private UserActor userActor;
public VkConnect(VkConfig vkConfig) {
this.vkConfig = vkConfig;
@ -35,6 +37,19 @@ public class VkConnect {
}
}
public UserActor getUserActor() {
if (userActor != null) {
return userActor;
} else {
initUserActor();
return userActor;
}
}
private void initUserActor() {
userActor = new UserActor(vkConfig.getConfigUser().getUserId(), vkConfig.getConfigUser().getToken());
}
public ServiceActor getServiceActor() {
if (serviceActor != null) {
return serviceActor;
@ -49,10 +64,10 @@ public class VkConnect {
}
private void initGroupActor() {
groupActor = new GroupActor(vkConfig.getGroupId(), vkConfig.getGroupToken());
groupActor = new GroupActor(vkConfig.getConfigGroup().getGroupId(), vkConfig.getConfigGroup().getGroupToken());
}
private void initServiceActor() {
serviceActor = new ServiceActor(vkConfig.getAppId(), vkConfig.getServiceToken());
serviceActor = new ServiceActor(vkConfig.getConfigService().getAppId(), vkConfig.getConfigService().getServiceToken());
}
}

View File

@ -0,0 +1,9 @@
package org.sadtech.vkbot.core.convert;
@FunctionalInterface
public interface Convert<T, C> {
C converting(T target);
}

View File

@ -5,17 +5,23 @@ import org.sadtech.bot.core.domain.keyboard.ButtonColor;
import org.sadtech.bot.core.domain.keyboard.KeyBoard;
import org.sadtech.bot.core.domain.keyboard.KeyBoardButton;
import org.sadtech.bot.core.domain.keyboard.KeyBoardLine;
import org.sadtech.bot.core.domain.keyboard.button.KeyBoardButtonAccount;
import org.sadtech.bot.core.domain.keyboard.button.KeyBoardButtonText;
import org.sadtech.vkbot.core.config.VkConnect;
import java.util.ArrayList;
import java.util.List;
public final class KeyBoardConvert {
public class KeyBoardConvert {
private KeyBoardConvert() {
private final VkConnect vkConnect;
public KeyBoardConvert(VkConnect vkConnect) {
this.vkConnect = vkConnect;
}
public static Keyboard convertKeyboard(KeyBoard keyboard) {
public Keyboard convertKeyboard(KeyBoard keyboard) {
Keyboard keyboardVk = new Keyboard();
keyboardVk.setOneTime(keyboard.isOneTime());
@ -32,20 +38,58 @@ public final class KeyBoardConvert {
return keyboardVk;
}
private static KeyboardButton convertButton(KeyBoardButton button) {
private KeyboardButton convertButton(KeyBoardButton button) {
KeyboardButton buttonVk = new KeyboardButton();
buttonVk.setColor(convertColor(button.getColor()));
KeyboardButtonAction buttonActionVk = new KeyboardButtonAction();
buttonActionVk.setLabel(button.getLabel());
buttonActionVk.setType(KeyboardButtonActionType.TEXT);
buttonActionVk.setPayload(button.getPayload());
switch (button.getType()) {
case TEXT:
KeyBoardButtonText buttonText = (KeyBoardButtonText) button;
buttonVk.setColor(convertColor(buttonText.getColor()));
break;
}
KeyboardButtonAction buttonActionVk = createActionButton(button);
buttonVk.setAction(buttonActionVk);
return buttonVk;
}
private KeyboardButtonAction createActionButton(KeyBoardButton button) {
KeyboardButtonAction keyboardButtonAction = new KeyboardButtonAction();
switch (button.getType()) {
case TEXT:
KeyBoardButtonText buttonText = (KeyBoardButtonText) button;
keyboardButtonAction.setType(KeyboardButtonActionType.TEXT);
keyboardButtonAction.setLabel(buttonText.getLabel());
break;
case ACCOUNT:
KeyBoardButtonAccount buttonAccount = (KeyBoardButtonAccount) button;
keyboardButtonAction.setType(KeyboardButtonActionType.VKPAY);
keyboardButtonAction.setHash(createHash(buttonAccount));
break;
}
return keyboardButtonAction;
}
private String createHash(KeyBoardButtonAccount button) {
StringBuilder stringBuilder = new StringBuilder();
if (button.getAmount()!=null) {
stringBuilder
.append("action=pay-to-group&amount=")
.append(button.getAmount()).append("&group_id=")
.append(vkConnect.getGroupActor().getGroupId());
} else {
stringBuilder
.append("action=transfer-to-group")
.append(button.getAmount()).append("&group_id=")
.append(vkConnect.getGroupActor().getGroupId());
}
if (button.getAccountId()!=null) {
stringBuilder.append("&description=").append(button.getAccountId());
}
return stringBuilder.append("&aid=").append(vkConnect.getServiceActor().getId()).toString();
}
private static KeyboardButtonColor convertColor(ButtonColor color) {
KeyboardButtonColor buttonColorVk;
switch (color) {

View File

@ -0,0 +1,53 @@
package org.sadtech.vkbot.core.convert;
import com.vk.api.sdk.objects.messages.Message;
import com.vk.api.sdk.objects.messages.MessageAttachment;
import org.sadtech.bot.core.domain.content.Mail;
import org.sadtech.bot.core.domain.content.attachment.Attachment;
import org.sadtech.bot.core.domain.content.attachment.AudioMessage;
import org.sadtech.bot.core.domain.content.attachment.Geo;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.TimeZone;
import java.util.stream.Collectors;
public class MessageMailConvert implements Convert<Message, Mail> {
@Override
public Mail converting(Message message) {
Mail mail = new Mail();
mail.setMessage(message.getText());
mail.setCreateDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(message.getDate()), TimeZone.getDefault().toZoneId()));
mail.setId(message.getId());
mail.setPersonId(message.getPeerId());
mail.setAttachments(message.getAttachments()
.stream()
.map(this::convertAttachment)
.collect(Collectors.toList()));
if (message.getGeo()!=null) {
mail.getAttachments().add(convertGeo(message.getGeo()));
}
return mail;
}
private Geo convertGeo(com.vk.api.sdk.objects.base.Geo geoVk) {
return Geo.builder()
.coordinate(geoVk.getCoordinates().getLatitude(),
geoVk.getCoordinates().getLongitude())
.city(geoVk.getPlace().getCity())
.build();
}
private Attachment convertAttachment(MessageAttachment vkAttachment) {
Attachment attachment = null;
switch (vkAttachment.getType()) {
case AUDIO_MESSAGE:
AudioMessage audioMessage = new AudioMessage();
audioMessage.setLinkOdd(vkAttachment.getAudioMessage().getLinkOgg());
attachment = audioMessage;
break;
}
return attachment;
}
}

View File

@ -0,0 +1,23 @@
package org.sadtech.vkbot.core.convert;
import com.vk.api.sdk.objects.board.TopicComment;
import org.sadtech.bot.core.domain.content.BoardComment;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.TimeZone;
public class TopicCommentToBoardComment implements Convert<TopicComment, BoardComment> {
@Override
public BoardComment converting(TopicComment target) {
BoardComment boardComment = new BoardComment();
boardComment.setContentId(target.getTopicId());
boardComment.setCreateDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(target.getDate()), TimeZone.getDefault().toZoneId()));
boardComment.setMessage(target.getText());
boardComment.setPersonId(target.getFromId());
System.out.println(target);
return boardComment;
}
}

View File

@ -0,0 +1,69 @@
package org.sadtech.vkbot.core.distribution;
import org.sadtech.vkbot.core.convert.Convert;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public abstract class AbstractBasketSubscribe<S, C> {
private Set<AbstractBasketSubscribe> basketSubscribes;
private AbstractBasketSubscribe prioritySubscribe;
protected Convert<S, C> convert;
public AbstractBasketSubscribe() {
convert = (object) -> (C) object;
}
protected abstract boolean check(S object);
public void update(S object) {
C newObject = convert.converting(object);
if (!goNextSubscribe(newObject)) {
processing(newObject);
}
}
private boolean goNextSubscribe(C object) {
AtomicBoolean flag = new AtomicBoolean(false);
if (prioritySubscribe != null && prioritySubscribe.check(object)) {
prioritySubscribe.update(object);
flag.set(true);
} else if (basketSubscribes != null) {
basketSubscribes.stream()
.filter(basketSubscribe -> basketSubscribe.check(object))
.forEach(basketSubscribe -> {
basketSubscribe.update(object);
flag.set(true);
});
}
return flag.get();
}
public abstract void processing(C object);
public Set<AbstractBasketSubscribe> getBasketSubscribes() {
return basketSubscribes;
}
public void setBasketSubscribes(Set<AbstractBasketSubscribe> basketSubscribes) {
this.basketSubscribes = basketSubscribes;
}
public AbstractBasketSubscribe getPrioritySubscribe() {
return prioritySubscribe;
}
public void setPrioritySubscribe(AbstractBasketSubscribe prioritySubscribe) {
this.prioritySubscribe = prioritySubscribe;
}
public Convert getConvert() {
return convert;
}
public void setConvert(Convert convert) {
this.convert = convert;
}
}

View File

@ -0,0 +1,54 @@
package org.sadtech.vkbot.core.distribution;
import com.vk.api.sdk.objects.messages.Message;
import com.vk.api.sdk.objects.messages.MessageAttachmentType;
import org.sadtech.bot.core.domain.BoxAnswer;
import org.sadtech.bot.core.exception.PaymentException;
import org.sadtech.bot.core.service.AccountService;
import org.sadtech.bot.core.service.sender.Sent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AccountSubscribe extends AbstractBasketSubscribe<Message, Message> {
private static final Logger log = LoggerFactory.getLogger(AccountSubscribe.class);
private final AccountService accountService;
private final Sent sent;
private BoxAnswer answerSuccessfulPayment;
public AccountSubscribe(AccountService accountService, Sent sent) {
this.accountService = accountService;
this.sent = sent;
}
@Override
protected boolean check(Message userMessage) {
return userMessage.getAttachments().size() > 0
&& MessageAttachmentType.LINK.equals(userMessage.getAttachments().get(0).getType())
&& "Payment awaiting acceptance".equals(userMessage.getAttachments().get(0).getLink().getCaption());
}
@Override
public void processing(Message message) {
if (message.getText() != null) {
try {
Integer valueSum = Integer.valueOf(message.getAttachments().get(0).getLink().getTitle().split(" ")[0]);
if (accountService.pay(Integer.valueOf(message.getText()), message.getPeerId(), valueSum) && answerSuccessfulPayment != null) {
sent.send(message.getPeerId(), answerSuccessfulPayment);
}
} catch (PaymentException e) {
log.error(e.getMessage());
sent.send(message.getPeerId(), BoxAnswer.builder().message(e.getDescription()).build());
}
}
}
public BoxAnswer getAnswerSuccessfulPayment() {
return answerSuccessfulPayment;
}
public void setAnswerSuccessfulPayment(BoxAnswer answerSuccessfulPayment) {
this.answerSuccessfulPayment = answerSuccessfulPayment;
}
}

View File

@ -0,0 +1,96 @@
package org.sadtech.vkbot.core.distribution;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.vk.api.sdk.objects.board.TopicComment;
import org.sadtech.bot.core.domain.content.BoardComment;
import org.sadtech.bot.core.service.BoardCommentService;
import org.sadtech.vkbot.core.convert.Convert;
import org.sadtech.vkbot.core.convert.TopicCommentToBoardComment;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BoardCommentSubscribe extends AbstractBasketSubscribe<JsonObject, TopicComment> {
private final BoardCommentService boardCommentService;
private final Convert<TopicComment, BoardComment> topicConvert = new TopicCommentToBoardComment();
private Set<Integer> answerTopicsId;
private Set<Integer> noAnswerPersonId;
private Boolean respondAppeal = true;
public BoardCommentSubscribe(BoardCommentService boardCommentService) {
this.boardCommentService = boardCommentService;
this.convert = (object) -> {
Gson gson = new Gson();
return gson.fromJson(object.getAsJsonObject("object"), TopicComment.class);
};
}
public Set<Integer> getAnswerTopicsId() {
return answerTopicsId;
}
public void setAnswerTopicsId(Set<Integer> answerTopicsId) {
this.answerTopicsId = answerTopicsId;
}
public Set<Integer> getNoAnswerPersonId() {
return noAnswerPersonId;
}
public void setNoAnswerPersonId(Set<Integer> noAnswerPersonId) {
this.noAnswerPersonId = noAnswerPersonId;
}
public Boolean getRespondAppeal() {
return respondAppeal;
}
public void setRespondAppeal(Boolean respondAppeal) {
this.respondAppeal = respondAppeal;
}
@Override
protected boolean check(JsonObject object) {
String type = object.get("type").getAsString();
return "board_post_new".equals(type);
}
@Override
public void processing(TopicComment object) {
if (checkPerson(object.getFromId())
&& checkTopic(object.getTopicId())
&& checkRespondAppeal(object.getText(), object.getFromId())) {
boardCommentService.add(topicConvert.converting(object));
}
}
private boolean checkRespondAppeal(String message, Integer groupId) {
if (respondAppeal) {
Pattern pattern = Pattern.compile("\\[club" + groupId);
Matcher m = pattern.matcher(message);
return m.find();
} else {
return true;
}
}
private boolean checkTopic(Integer topicId) {
if (answerTopicsId == null) {
return true;
} else {
return answerTopicsId.contains(topicId);
}
}
private boolean checkPerson(Integer personId) {
if (noAnswerPersonId == null) {
return true;
} else {
return !noAnswerPersonId.contains(personId);
}
}
}

View File

@ -4,45 +4,35 @@ 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 class EventDistributor extends AbstractBasketSubscribe<JsonObject, JsonObject> implements Runnable {
private static final Logger log = Logger.getLogger(EventDistributor.class);
private final RawEventService rawEventService;
private final Map<String, EventSubscribe> eventDistributionMap = new HashMap<>();
public EventDistributor(RawEventService rawEventService) {
this.rawEventService = rawEventService;
log.info("EventDistributor инициализирован");
}
public void update() {
@Override
public void run() {
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;
if (rawEventService.getJsonObjects().peek() != null) {
JsonObject event = rawEventService.getJsonObjects().poll();
log.info("Добавлено новое событие");
super.update(event);
}
}
}
public void setEventDistributionMap(String key, EventSubscribe eventSubscribe) {
this.eventDistributionMap.put(key, eventSubscribe);
@Override
protected boolean check(JsonObject object) {
return false;
}
@Override
public void run() {
log.info("EventDistributor запущен");
update();
public void processing(JsonObject object) {
}
}

View File

@ -1,7 +0,0 @@
package org.sadtech.vkbot.core.distribution;
public interface EventSubscribe<T> {
void update(T object);
}

View File

@ -3,92 +3,33 @@ 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 com.vk.api.sdk.objects.messages.MessageAttachment;
import com.vk.api.sdk.objects.messages.MessageAttachmentType;
import org.apache.log4j.Logger;
import org.sadtech.bot.core.domain.Mail;
import org.sadtech.bot.core.domain.attachment.Attachment;
import org.sadtech.bot.core.domain.attachment.AudioMessage;
import org.sadtech.bot.core.domain.content.Mail;
import org.sadtech.bot.core.service.MailService;
import org.sadtech.vkbot.core.convert.Convert;
import org.sadtech.vkbot.core.convert.MessageMailConvert;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
public class MailSubscriber implements EventSubscribe<JsonObject> {
private static final Logger log = Logger.getLogger(MailSubscriber.class);
public class MailSubscriber extends AbstractBasketSubscribe<JsonObject, Message> {
private final MailService mailService;
private Set<Integer> admins = new HashSet<>();
private final Map<String, EventSubscribe<Message>> eventDistributionMap = new HashMap<>();
private final Convert<Message, Mail> mailConvert = new MessageMailConvert();
public MailSubscriber(MailService mailService) {
this.mailService = mailService;
}
public void setAdmins(Set<Integer> admins) {
this.admins = admins;
}
public Set<Integer> getAdmins() {
return admins;
this.convert = (object) -> {
Gson gson = new Gson();
return gson.fromJson(object.getAsJsonObject("object"), Message.class);
};
}
@Override
public void update(JsonObject object) {
log.info("Дистрибьютор получил событие - сообщение");
Gson gson = new Gson();
Message userMessage = gson.fromJson(object, Message.class);
log.info(userMessage);
if (userMessage.getPeerId() > 2000000000) {
if (eventDistributionMap.containsKey("chat")) {
eventDistributionMap.get("chat").update(userMessage);
}
} else {
if (admins.contains(userMessage.getPeerId()) && eventDistributionMap.containsKey("terminal")) {
log.info("Сообщение отправлено в репозиторий команд");
eventDistributionMap.get("terminal").update(userMessage);
} else {
log.info("Сообщение отправленно на добавление в репозиторий");
mailService.add(createMaail(userMessage));
}
}
protected boolean check(JsonObject object) {
String type = object.get("type").getAsString();
return "message_new".equals(type);
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
private Mail createMaail(Message message) {
Mail mail = new Mail();
mail.setMessage(message.getText());
mail.setDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(message.getDate()), TimeZone.getDefault().toZoneId()));
mail.setId(message.getId());
mail.setPersonId(message.getPeerId());
List<Attachment> attachments = new ArrayList<>();
for (MessageAttachment attachment : message.getAttachments()) {
if (MessageAttachmentType.AUDIO_MESSAGE.equals(attachment.getType())) {
AudioMessage audioMessage = new AudioMessage();
audioMessage.setLinkOdd(attachment.getAudioMessage().getLinkOgg());
attachments.add(audioMessage);
}
}
mail.setAttachments(attachments);
return mail;
@Override
public void processing(Message object) {
mailService.add(mailConvert.converting(object));
}
}

View File

@ -0,0 +1,8 @@
package org.sadtech.vkbot.core.exception;
public class ConfigException extends RuntimeException {
public ConfigException(String message) {
super(message);
}
}

View File

@ -1,18 +1,17 @@
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.callback.longpoll.responses.GetLongPollEventsResponse;
import com.vk.api.sdk.objects.groups.LongPollServer;
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;
import org.sadtech.vkbot.core.config.VkConnect;
public class EventListenerVk implements Runnable {
@ -20,9 +19,7 @@ public class EventListenerVk implements Runnable {
private final VkApiClient vk;
private final GroupActor actor;
private static final Integer DEFAULT_WAIT_TIME = 25;
private final RawEventService rawEventService;
public EventListenerVk(VkConnect vkConnect) {
@ -32,31 +29,30 @@ public class EventListenerVk implements Runnable {
}
public EventListenerVk(VkConnect vkConnect, RawEventService rawEventService) {
this.vk = vkConnect.getVkApiClient();
this.actor = vkConnect.getGroupActor();
vk = vkConnect.getVkApiClient();
actor = vkConnect.getGroupActor();
this.rawEventService = rawEventService;
}
public RawEventService getRawEventService() {
return rawEventService;
}
public void listen() throws ClientException, ApiException {
LongPollServer longPollServer = getLongPollServer();
int lastTimeStamp = longPollServer.getTs();
int lastTimeStamp = Integer.parseInt(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);
}
GetLongPollEventsResponse eventsResponse = vk.longPoll()
.getEvents(longPollServer.getServer(), longPollServer.getKey(), lastTimeStamp)
.waitTime(DEFAULT_WAIT_TIME)
.execute();
eventsResponse.getUpdates().parallelStream().forEach(object -> {
log.info("Новое событие от LongPoll\n" + object);
rawEventService.add(object);
});
lastTimeStamp = eventsResponse.getTs();
} catch (LongPollServerKeyExpiredException e) {
log.error(e.getStackTrace());
log.error(e.getMessage());
longPollServer = getLongPollServer();
} catch (Exception e) {
log.error(e.getStackTrace());
log.error(e.getMessage());
break;
}
}
@ -76,8 +72,12 @@ public class EventListenerVk implements Runnable {
try {
listen();
} catch (ClientException | ApiException e) {
log.error(e);
log.error(e.getMessage());
}
}
public RawEventService getRawEventService() {
return rawEventService;
}
}

View File

@ -0,0 +1,59 @@
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.client.actors.UserActor;
import com.vk.api.sdk.exceptions.ApiException;
import com.vk.api.sdk.exceptions.ClientException;
import org.sadtech.bot.core.domain.BoxAnswer;
import org.sadtech.bot.core.domain.keyboard.KeyBoardButton;
import org.sadtech.bot.core.domain.keyboard.KeyBoardLine;
import org.sadtech.bot.core.domain.keyboard.button.KeyBoardButtonText;
import org.sadtech.bot.core.exception.MailSendException;
import org.sadtech.bot.core.service.sender.Sent;
import org.sadtech.vkbot.core.config.VkConnect;
import org.sadtech.vkbot.core.utils.VkInsertData;
public class BoardCommentSenderVk implements Sent {
private final VkApiClient vkApiClient;
private final GroupActor groupActor;
private final UserActor userActor;
private final VkInsertData vkInsertData;
public BoardCommentSenderVk(VkConnect vkConnect) {
this.vkApiClient = vkConnect.getVkApiClient();
this.groupActor = vkConnect.getGroupActor();
this.vkInsertData = new VkInsertData(vkConnect);
this.userActor = vkConnect.getUserActor();
}
@Override
public void send(Integer integer, BoxAnswer boxAnswer) {
throw new MailSendException();
}
@Override
public void send(Integer contentId, Integer personId, BoxAnswer boxAnswer) {
try {
StringBuilder insertAnswer = new StringBuilder(vkInsertData.insertWords(boxAnswer.getMessage(), personId));
if (boxAnswer.getKeyboard() != null) {
insertAnswer.append("\n\nМеню:\n");
for (KeyBoardLine keyBoardLine : boxAnswer.getKeyboard().getKeyBoardLines()) {
for (KeyBoardButton keyBoardButton : keyBoardLine.getKeyBoardButtons()) {
switch (keyBoardButton.getType()) {
case TEXT:
insertAnswer.append("- ").append(((KeyBoardButtonText)keyBoardButton).getLabel()).append("\n");
}
}
}
}
vkApiClient.board().createComment(userActor, groupActor.getGroupId(), contentId)
.message(insertAnswer.toString()).fromGroup(true).execute();
} catch (ApiException | ClientException e) {
e.printStackTrace();
}
}
}

View File

@ -1,6 +1,5 @@
package org.sadtech.vkbot.core.sender;
import com.google.gson.Gson;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.GroupActor;
import com.vk.api.sdk.exceptions.ApiException;
@ -9,10 +8,11 @@ import com.vk.api.sdk.objects.messages.Keyboard;
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;
import org.sadtech.bot.core.domain.keyboard.KeyBoard;
import org.sadtech.bot.core.service.sender.Sent;
import org.sadtech.vkbot.core.config.VkConnect;
import org.sadtech.vkbot.core.convert.KeyBoardConvert;
import org.sadtech.vkbot.core.utils.VkInsertData;
import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;
@ -23,51 +23,52 @@ public class MailSenderVk implements Sent {
private final VkApiClient vkApiClient;
private final GroupActor groupActor;
private final VkInsertData vkInsertData;
private final Gson gson = new Gson();
private final KeyBoardConvert keyBoardConvert;
public MailSenderVk(VkConnect vkConnect) {
this.vkApiClient = vkConnect.getVkApiClient();
this.groupActor = vkConnect.getGroupActor();
this.vkInsertData = new VkInsertData(vkConnect);
keyBoardConvert = new KeyBoardConvert(vkConnect);
}
@Override
public void send(Integer idPerson, String message) {
sendMessage(vkApiClient.messages().send(groupActor).peerId(idPerson).message(message).randomId(ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE)));
}
@Override
public void send(Integer idPerson, BoxAnswer boxAnswer) {
MessagesSendQuery messagesSendQuery = createMessage(boxAnswer, idPerson);
public void send(Integer personId, BoxAnswer boxAnswer) {
MessagesSendQuery messagesSendQuery = createMessage(boxAnswer, personId);
sendMessage(messagesSendQuery);
}
private MessagesSendQuery createMessage(BoxAnswer boxAnswer, Integer peerId) {
MessagesSendQuery messages = vkApiClient.messages().send(groupActor).peerId(peerId).message(vkInsertData.insertWords(boxAnswer.getMessage(), peerId)).randomId(ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE));
if (boxAnswer.getKeyboard() != null) {
messages.keyboard(KeyBoardConvert.convertKeyboard(boxAnswer.getKeyboard()));
} else {
Keyboard keyboard = new Keyboard();
keyboard.setOneTime(true);
keyboard.setButtons(Collections.EMPTY_LIST);
messages.keyboard(keyboard);
}
if (boxAnswer.getLat() != null && boxAnswer.getaLong() != null) {
messages.lat(boxAnswer.getLat()).lng(boxAnswer.getaLong());
MessagesSendQuery messages = vkApiClient.messages().send(groupActor).peerId(peerId)
.message(vkInsertData.insertWords(boxAnswer.getMessage(), peerId))
.randomId(ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE));
messages.keyboard(convertKeyBoard(boxAnswer.getKeyboard()));
if (boxAnswer.getCoordinates() != null) {
messages.lat(boxAnswer.getCoordinates().getLatitude()).lng(boxAnswer.getCoordinates().getLongitude());
}
if (boxAnswer.getStickerId() != null) {
try {
vkApiClient.messages().send(groupActor).peerId(peerId).stickerId(boxAnswer.getStickerId()).execute();
vkApiClient.messages().send(groupActor).peerId(peerId).stickerId(boxAnswer.getStickerId())
.randomId(ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE)).execute();
} catch (ApiException | ClientException e) {
log.error(e);
log.error(e.getMessage());
}
}
return messages;
}
private Keyboard convertKeyBoard(KeyBoard keyboard) {
if (keyboard != null) {
return keyBoardConvert.convertKeyboard(keyboard);
} else {
Keyboard keyboardVk = new Keyboard();
keyboardVk.setOneTime(true);
keyboardVk.setButtons(Collections.EMPTY_LIST);
return keyboardVk;
}
}
private void sendMessage(MessagesSendQuery messages) {
@ -78,5 +79,9 @@ public class MailSenderVk implements Sent {
}
}
@Override
public void send(Integer integer, Integer integer1, BoxAnswer boxAnswer) {
}
}

View File

@ -1,74 +0,0 @@
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 {
private static final Logger log = Logger.getLogger(PersonServiceImpl.class);
private final PersonRepository personRepository;
private final 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;
}
}

View File

@ -1,16 +1,17 @@
package org.sadtech.vkbot.core;
package org.sadtech.vkbot.core.utils;
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.client.actors.ServiceActor;
import com.vk.api.sdk.exceptions.ApiException;
import com.vk.api.sdk.exceptions.ClientException;
import com.vk.api.sdk.objects.users.Fields;
import com.vk.api.sdk.objects.users.UserMin;
import com.vk.api.sdk.objects.users.UserXtrCounters;
import org.apache.log4j.Logger;
import org.sadtech.vkbot.core.config.VkConnect;
import java.util.List;
@ -19,11 +20,11 @@ public class VkApi {
private static final Logger log = Logger.getLogger(String.valueOf(VkApi.class));
private final VkApiClient vk;
private final GroupActor actor;
private final ServiceActor actor;
public VkApi(VkConnect vkConnect) {
vk = vkConnect.getVkApiClient();
actor = vkConnect.getGroupActor();
actor = vkConnect.getServiceActor();
}
public UserMin getUserMini(Integer id) {

View File

@ -1,4 +1,6 @@
package org.sadtech.vkbot.core;
package org.sadtech.vkbot.core.utils;
import org.sadtech.vkbot.core.config.VkConnect;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -11,12 +13,12 @@ public class VkInsertData {
this.vkApi = new VkApi(vkConnect);
}
public String insertWords(String message, Integer idUser) {
public String insertWords(String message, Integer personId) {
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.appendReplacement(result, insert(m.group(0), personId));
}
m.appendTail(result);
return result.toString();