Без понятия

This commit is contained in:
Mark Struchkov 2019-04-29 12:12:38 +03:00
commit 6563cf3a53
22 changed files with 1064 additions and 0 deletions

57
pom.xml Normal file
View File

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sadtech.vkbot</groupId>
<artifactId>vkbot-core</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<vksdk.ver>0.5.13-SNAPSHOT</vksdk.ver>
<log4j.ver>1.2.17</log4j.ver>
</properties>
<dependencies>
<dependency>
<groupId>com.vk.api</groupId>
<artifactId>sdk</artifactId>
<version>${vksdk.ver}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.ver}</version>
</dependency>
<dependency>
<groupId>org.sadtech.bot</groupId>
<artifactId>bot-core</artifactId>
<version>0.4.3-SNAPSHOT</version>
</dependency>
</dependencies>
<developers>
<developer>
<name>Struchkov Mark</name>
<email>upagge@mail.ru</email>
</developer>
</developers>
</project>

View File

@ -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<UserXtrCounters> 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<UserXtrCounters> 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<UserXtrCounters> 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<UserXtrCounters> temp) {
log.info("Запрошен город пользователя: " + temp.get(0).getCity().getTitle());
return temp.get(0).getCity() != null;
}
}

View File

@ -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);
}
}

View File

@ -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());
}
}

View File

@ -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;
}
}

View File

@ -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<JsonObject> {
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);
}
}

View File

@ -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<String, EventSubscribe> 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();
}
}

View File

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

View File

@ -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<JsonObject> {
public static final Logger log = Logger.getLogger(MailSubscriber.class);
private MailService mailService;
private Set<Integer> admins = new HashSet<>();
private Map<String, EventSubscribe<Message>> eventDistributionMap = new HashMap<>();
public MailSubscriber(MailService mailService) {
this.mailService = mailService;
}
public void setAdmins(Set<Integer> admins) {
this.admins = admins;
}
public Set<Integer> 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;
}
}

View File

@ -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<Message> {
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("Сообщение отправленно на добавление в репозиторий команд");
}
}

View File

@ -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;
}
}
}

View File

@ -0,0 +1,7 @@
package org.sadtech.vkbot.core.keyboard;
public enum ColorButton {
PRIMARY, DEFAULT, NEGATIVE, POSITIVE
}

View File

@ -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<LineKeyBoard> lineKeyBoards = new ArrayList<>();
private boolean oneTime;
public KeyBoard() {
}
public KeyBoard(List<LineKeyBoard> 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;
}
}
}

View File

@ -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<String> 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<ButtonKeyBoard> buttonKeyBoards) {
KeyBoard keyBoard = new KeyBoard();
for (ButtonKeyBoard buttonKeyBoard : buttonKeyBoards) {
keyBoard.addLine(LineKeyBoard.builder().setButtonKeyBoard(buttonKeyBoard).build());
}
keyBoard.setOneTime(true);
return keyBoard;
}
}

View File

@ -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<ButtonKeyBoard> buttonKeyBoards = new ArrayList<>();
public LineKeyBoard() {
}
public LineKeyBoard(List<ButtonKeyBoard> 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;
}
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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;
}
}

View File

@ -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<Comment> {
}

View File

@ -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<Mail> {
}

View File

@ -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<Comment> getEvent(Integer timeFrom, Integer timeTo) {
return null;
}
@Override
public List<Comment> getFirstEventByTime(Integer timeFrom, Integer timeTo) {
return null;
}
@Override
public List<Comment> getLastEventByTime(Integer timeFrom, Integer timeTo) {
return null;
}
}

View File

@ -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<Mail> getFirstEventByTime(Integer timeFrom, Integer timeTo) {
log.info("Запрошены сообщения " + timeFrom + "-" + timeTo);
List<Mail> mails = mailRepository.getMailByTime(timeFrom, timeTo);
Set<Integer> people = new HashSet<>();
List<Mail> 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<Mail> getLastEventByTime(Integer timeFrom, Integer timeTo) {
List<Mail> mails = mailRepository.getMailByTime(timeFrom, timeTo);
Set<Integer> people = new HashSet<>();
List<Mail> returnMails = new ArrayList<>();
for (Mail mail : mails) {
if (!people.contains(mail.getPeerId())) {
returnMails.add(mail);
people.add(mail.getPeerId());
}
}
return returnMails;
}
@Override
public List<Mail> getEvent(Integer timeFrom, Integer timeTo) {
log.info("Запрос на получение сообщений в интервале от " + timeFrom + " до " + timeTo);
return mailRepository.getMailByTime(timeFrom, timeTo);
}
}