WARNING! not worked code in DeferredMessageListener -> DeferredMessageService

pull/2/head
Vyacheslav N. Boyko 2018-01-31 22:05:04 +03:00
parent ecb08c4bf1
commit 497bfb07df
16 changed files with 438 additions and 17 deletions

3
.gitignore vendored
View File

@ -47,3 +47,6 @@ google-search.txt
yandex-search.txt
target
jircbot.sqlite

View File

@ -0,0 +1,89 @@
package ru.bvn13.jircbot;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
/**
* Created by bvn13 on 30.01.2018.
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = MainApp.class)
public class JpaConfig {
@Value("${spring.dataSource.driverClassName}")
private String driver;
@Value("${spring.dataSource.url}")
private String url;
@Value("${spring.dataSource.username}")
private String username;
@Value("${spring.dataSource.password}")
private String password;
@Value("${spring.hibernate.dialect}")
private String dialect;
@Value("${spring.hibernate.hbm2ddl.auto}")
private String hbm2ddlAuto;
@Value("${spring.hibernate.show_sql}")
private Boolean showSql;
@Value("${spring.hibernate.use_sql_comments}")
private Boolean useSqlComments;
@Value("${spring.hibernate.format_sql}")
private Boolean formatSql;
@Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setDriverClassName(driver);
config.setJdbcUrl(url);
config.setUsername(username);
config.setPassword(password);
config.addDataSourceProperty("useUnicode", "true");
config.addDataSourceProperty("characterEncoding", "utf8");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("useServerPrepStmts", "true");
return new HikariDataSource(config);
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan("ru.bvn13.jircbot");
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put(org.hibernate.cfg.Environment.DIALECT, dialect);
jpaProperties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, hbm2ddlAuto);
jpaProperties.put(org.hibernate.cfg.Environment.SHOW_SQL, showSql);
//jpaProperties.put(org.hibernate.cfg.Environment.USE_SQL_COMMENTS, useSqlComments);
jpaProperties.put(org.hibernate.cfg.Environment.FORMAT_SQL, formatSql);
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new JpaTransactionManager();
}
}

View File

@ -3,13 +3,14 @@ package ru.bvn13.jircbot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import ru.bvn13.jircbot.bot.JircBot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAutoConfiguration
@EnableAutoConfiguration//(exclude={DataSourceAutoConfiguration.class})
@ComponentScan("ru.bvn13.jircbot")
public class MainApp implements CommandLineRunner {

View File

@ -0,0 +1,16 @@
package ru.bvn13.jircbot.bot;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericEvent;
/**
* Created by bvn13 on 31.01.2018.
*/
public class ImprovedListenerAdapter extends ListenerAdapter {
protected void sendNotice(GenericEvent event, String str) {
event.getBot().sendIRC().notice(((MessageEvent) event).getChannel().getName(), str);
}
}

View File

@ -59,13 +59,14 @@ public class JircBot extends ListenerAdapter {
private BashOrgListener bashOrgListener;
@Autowired
private AutoRejoinListener autoRejoinListener;
@Autowired
private DeferredMessagesListener deferredMessagesListener;
@Autowired
private LinkPreviewListener linkPreviewListener;
@Autowired
private HelloOnJoinListener helloOnJoinListener;
@PostConstruct
public void start() {
@ -80,7 +81,7 @@ public class JircBot extends ListenerAdapter {
List<Configuration.ServerEntry> servers = new ArrayList<>();
servers.add(new Configuration.ServerEntry(c.getServer(), c.getPort()));
this.bots.put(
String.format("%s/%s", c.getServer(), "1"), //c.getChannelName()),
String.format("%s/%s", c.getServer(), "1"),
new PircBotX(templateConfig
.setName(c.getBotName())
.addListener(pingPongListener)
@ -90,6 +91,7 @@ public class JircBot extends ListenerAdapter {
.addListener(quizListener)
.addListener(bashOrgListener)
.addListener(autoRejoinListener)
.addListener(deferredMessagesListener)
// disabled yet
//.addListener(linkPreviewListener)

View File

@ -0,0 +1,70 @@
package ru.bvn13.jircbot.database.entities;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Created by bvn13 on 31.01.2018.
*/
@MappedSuperclass
public abstract class BaseModel implements Comparable<BaseModel>, Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(nullable = false)
private Date createdAt;
@Column(nullable = false)
private Date updatedAt;
@PrePersist
public void prePersist(){
createdAt = updatedAt = new Date();
}
@PreUpdate
public void preUpdate(){
updatedAt = new Date();
}
@Override
public int compareTo(BaseModel o) {
return this.getId().compareTo(o.getId());
}
public int hashCode() {
return new HashCodeBuilder().append(getId()).toHashCode();
}
public Long getId() {
return id;
}
public void setId(Long _id) {
id = _id;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@ -0,0 +1,47 @@
package ru.bvn13.jircbot.database.entities;
import lombok.Getter;
import lombok.Setter;
/**
* Created by bvn13 on 31.01.2018.
*/
public class ChannelSettings extends BaseModel {
@Getter
@Setter
private String channelName;
@Getter
@Setter
private String botName;
@Getter
@Setter
private Boolean pingPongEnabled;
@Getter
@Setter
private Boolean calculatorEnabled;
@Getter
@Setter
private Boolean regexCheckerEnabled;
@Getter
@Setter
private Boolean adviceEnabled;
@Getter
@Setter
private Boolean quizEnabled;
@Getter
@Setter
private Boolean bashOrgEnabled;
@Getter
@Setter
private Boolean autoRejoinEnabled;
}

View File

@ -0,0 +1,40 @@
package ru.bvn13.jircbot.database.entities;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Type;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
* Created by bvn13 on 31.01.2018.
*/
@Entity
@Table(name = "deferred_messages")
public class DeferredMessage extends BaseModel {
@Getter
@Setter
private String sender;
@Getter
@Setter
private String recipient;
@Getter
@Setter
@Type(type = "text")
private String message;
@Getter
private Boolean sent;
public Boolean isSent() {
return sent;
}
public void setSent(Boolean sent) {
this.sent = sent;
}
}

View File

@ -0,0 +1,15 @@
package ru.bvn13.jircbot.database.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ru.bvn13.jircbot.database.entities.DeferredMessage;
import java.util.List;
/**
* Created by bvn13 on 31.01.2018.
*/
@Repository
public interface DeferredMessageRepository extends JpaRepository<DeferredMessage, Long> {
List<DeferredMessage> getDeferredMessagesByRecipientAndSentOrderByCreatedAt(String recipient, Boolean sent);
}

View File

@ -0,0 +1,43 @@
package ru.bvn13.jircbot.database.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.bvn13.jircbot.database.entities.DeferredMessage;
import ru.bvn13.jircbot.database.repositories.DeferredMessageRepository;
import java.util.Date;
import java.util.List;
/**
* Created by bvn13 on 31.01.2018.
*/
@Service
public class DeferredMessageService {
@Autowired
private DeferredMessageRepository deferredMessageRepository;
public List<DeferredMessage> getDeferredMessagesForUser(String user) {
return deferredMessageRepository.getDeferredMessagesByRecipientAndSentOrderByCreatedAt(user, false);
}
public void saveDeferredMessage(String sender, String recipient, String message) {
DeferredMessage msg = new DeferredMessage();
msg.setId(1L);
msg.setCreatedAt(new Date());
msg.setUpdatedAt(new Date());
msg.setSender(sender);
msg.setRecipient(recipient);
msg.setMessage(message);
msg.setSent(false);
deferredMessageRepository.save(msg);
}
public void markMessageWasSent(DeferredMessage msg) {
msg.setSent(true);
deferredMessageRepository.save(msg);
}
}

View File

@ -6,13 +6,14 @@ import org.pircbotx.hooks.events.KickEvent;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.springframework.stereotype.Component;
import ru.bvn13.jircbot.bot.ImprovedListenerAdapter;
import ru.bvn13.jircbot.listeners.advices.AdviceEngine;
/**
* Created by bvn13 on 27.01.2018.
*/
@Component
public class AutoRejoinListener extends ListenerAdapter {
public class AutoRejoinListener extends ImprovedListenerAdapter {
private Boolean wasKicked = false;
private String offender = "";
@ -33,7 +34,7 @@ public class AutoRejoinListener extends ListenerAdapter {
if (wasKicked) {
wasKicked = false;
event.getBot().sendIRC().notice(event.getChannel().getName(), ""+offender+", "+ AdviceEngine.getAdvice());
this.sendNotice(event, ""+offender+", "+ AdviceEngine.getAdvice());
}
}

View File

@ -8,6 +8,7 @@ import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.springframework.stereotype.Component;
import ru.bvn13.jircbot.bot.ImprovedListenerAdapter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@ -18,7 +19,7 @@ import java.net.URL;
* Created by bvn13 on 26.01.2018.
*/
@Component
public class BashOrgListener extends ListenerAdapter {
public class BashOrgListener extends ImprovedListenerAdapter {
private static final String COMMAND = "?bash";
private static final String USER_AGENT = "Mozilla/5.0";
@ -35,7 +36,7 @@ public class BashOrgListener extends ListenerAdapter {
}
try {
sendNotice(event, getRandomBashQuote());
this.sendNotice(event, getRandomBashQuote());
} catch (Exception e) {
event.respond("ОШИБКА: "+e.getMessage());
e.printStackTrace();
@ -43,10 +44,6 @@ public class BashOrgListener extends ListenerAdapter {
}
private void sendNotice(GenericMessageEvent event, String str) {
event.getBot().sendIRC().notice(((MessageEvent) event).getChannel().getName(), str);
}
private String getDataFromConnection(HttpURLConnection con) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "windows-1251"));
String inputLine;

View File

@ -0,0 +1,75 @@
package ru.bvn13.jircbot.listeners;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.bvn13.jircbot.bot.ImprovedListenerAdapter;
import ru.bvn13.jircbot.database.entities.DeferredMessage;
import ru.bvn13.jircbot.database.services.DeferredMessageService;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* Created by bvn13 on 31.01.2018.
*/
@Component
public class DeferredMessagesListener extends ImprovedListenerAdapter {
private static final String COMMAND = "?tell";
private static SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Autowired
private DeferredMessageService deferredMessageService;
@Override
public void onGenericMessage(final GenericMessageEvent event) throws Exception {
if (event.getUser().getUserId().equals(event.getBot().getUserBot().getUserId())) {
return;
}
//this.sendDeferredMessage(event);
if (!event.getMessage().startsWith(COMMAND)) {
return;
}
String message = event.getMessage().replace(COMMAND, "").trim();
String commands[] = message.split(" ", 2);
if (commands.length != 2) {
event.respond("Deferred messages usage: ?tell <UserNick/ME> your message");
return;
}
String userName = event.getUser().getNick();
if (commands[0].equalsIgnoreCase("me")) {
// deferred to myself
deferredMessageService.saveDeferredMessage(userName, userName.toLowerCase(), commands[1]);
event.respond("Saved message to "+userName);
} else {
// deferred to somebody
deferredMessageService.saveDeferredMessage(userName, commands[0].toLowerCase(), commands[1]);
event.respond("Saved message to "+commands[0]);
}
}
private void sendDeferredMessage(final GenericMessageEvent event) {
List<DeferredMessage> deferredMessages = deferredMessageService.getDeferredMessagesForUser(event.getUser().getNick().toLowerCase());
if (deferredMessages != null) {
deferredMessages.forEach(msg -> {
event.respond("User "+msg.getSender()+" at "+dt.format(msg.getCreatedAt())+" tell you: "+msg.getMessage());
deferredMessageService.markMessageWasSent(msg);
});
}
}
}

View File

@ -4,12 +4,13 @@ import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.events.MessageEvent;
import org.springframework.stereotype.Component;
import ru.bvn13.jircbot.bot.ImprovedListenerAdapter;
/**
* Created by bvn13 on 25.01.2018.
*/
@Component
public class HelloOnJoinListener extends ListenerAdapter {
public class HelloOnJoinListener extends ImprovedListenerAdapter {
@Override
public void onJoin(final JoinEvent event) throws Exception {
@ -18,8 +19,8 @@ public class HelloOnJoinListener extends ListenerAdapter {
return;
}
//event.respond("hello!");
event.getBot().sendIRC().notice(event.getChannel().getName(), "Привет, "+event.getUser().getNick()+"!");
//event.respond("Привет, "+event.getUser().getNick()+"!");
this.sendNotice(event, "Привет, "+event.getUser().getNick()+"!");
}

View File

@ -4,6 +4,7 @@ import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.springframework.stereotype.Component;
import ru.bvn13.jircbot.bot.ImprovedListenerAdapter;
import java.io.*;
import java.net.HttpURLConnection;
@ -23,7 +24,7 @@ import static java.lang.System.out;
* Created by bvn13 on 23.01.2018.
*/
@Component
public class LinkPreviewListener extends ListenerAdapter {
public class LinkPreviewListener extends ImprovedListenerAdapter {
private static final Pattern REGEX = Pattern.compile("(?i)(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\\.?)(?::\\d{2,5})?(?:[/?#]\\S*)?");
@ -39,7 +40,7 @@ public class LinkPreviewListener extends ListenerAdapter {
for (String link : links) {
String info = parseLink(link);
if (info != null && !info.isEmpty()) {
event.getBot().sendIRC().notice(((MessageEvent) event).getChannel().getName(), info);
this.sendNotice(event, info);
}
};

View File

@ -1,4 +1,24 @@
server:
port: 8080
address: localhost
name: jircbot
config: config.json
config: config.json
spring:
dataSource:
driverClassName: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/jircbot
username: jircbot
password: jircbotpass
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
hbm2ddl.auto: update
show_sql: true
use_sql_comments: true
format_sql: true