Skip to content

Commit

Permalink
formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
ulasakdeniz committed Nov 1, 2016
1 parent d5e162f commit 89229f8
Show file tree
Hide file tree
Showing 11 changed files with 155 additions and 155 deletions.
18 changes: 9 additions & 9 deletions app/Module.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@
* This class is a Guice module that tells Guice how to bind several
* different types. This Guice module is created when the Play
* application starts.
*
* <p>
* Play will automatically use any class called `Module` that is in
* the root package. You can create modules in other locations by
* adding `play.modules.enabled` settings to the `application.conf`
* configuration file.
*/
public class Module extends AbstractModule {

@Override
public void configure() {
@Override
public void configure() {

bind(BotRegisterer.class).asEagerSingleton();
bind(BotRegisterer.class).asEagerSingleton();

bind(BotFather.class).asEagerSingleton();
bind(BotFather.class).asEagerSingleton();

bind(TelegramBot.class).asEagerSingleton();
bind(TelegramBot.class).asEagerSingleton();

bind(FacebookBot.class).asEagerSingleton();
bind(FacebookBot.class).asEagerSingleton();

bind(RedisHelper.class).asEagerSingleton();
}
bind(RedisHelper.class).asEagerSingleton();
}
}
11 changes: 5 additions & 6 deletions app/bots/BotFather.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,9 @@ public BotFather(RedisHelper redisHelper, DBHelper dbHelper) {
recipient.thenApplyAsync(recipientUser -> {
//TODO: multiple recipient case!!!
String sId = redisHelper.getUserId(message.getSenderClient(), message.getSender());
if(recipientUser != null && sId != null) {
if (recipientUser != null && sId != null) {
send(recipientUser, sId, text);
}
else {
} else {
Logger.warn("Either recipientUser or sId or both are null");
}
return null;
Expand Down Expand Up @@ -74,18 +73,18 @@ void registerBot(String botName, Bot bot) {
CompletionStage<String> registerUser(User user) {
CompletionStage<User> existsInRedis = redisHelper.getUser(user.getId());
return existsInRedis.thenComposeAsync(redisUser -> {
if(redisUser != null) {
if (redisUser != null) {
return CompletableFuture.completedFuture(UserMessages.USER_ALREADY_EXISTS);
} else {
CompletionStage<DBResult> dbFuture = dbHelper.addUser(user);
return dbFuture.thenComposeAsync(dbResult -> {
if(dbResult.isSuccess()) {
if (dbResult.isSuccess()) {
redisHelper.addUser(user);
return CompletableFuture.completedFuture(UserMessages.USER_REGISTERED);
} else {
DBFailureResult dbFailureResult = (DBFailureResult) dbResult;
int reason = dbFailureResult.getReason();
if(reason == Contract.DUPLICATE_ENTRY) {
if (reason == Contract.DUPLICATE_ENTRY) {
return CompletableFuture.completedFuture(UserMessages.USER_ALREADY_EXISTS);
} else {
return CompletableFuture.completedFuture(UserMessages.USER_NOT_REGISTERED);
Expand Down
8 changes: 4 additions & 4 deletions app/bots/FacebookBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ public boolean receive(JsonNode json) {
Logger.debug("SenderID: " + senderId + " text: " + node.toString());

if (!text.isEmpty() && !senderId.isEmpty()) {
if(text.startsWith("+signup")) {
if (text.startsWith("+signup")) {
String userId = MessageParser.extractUserId(text);
CompletionStage<String> completionStageName = getUserNameFromFacebook(senderId);
completionStageName.thenApplyAsync(name -> {
if(name != null && userId != null && !userId.isEmpty()) {
if (name != null && userId != null && !userId.isEmpty()) {
botFather.registerUser(new User(userId, name, Contract.FACEBOOK, senderId)).thenApplyAsync(dbMessage -> {
sendMessage(senderId, dbMessage);
return null;
Expand Down Expand Up @@ -84,11 +84,11 @@ public void sendMessage(String recipient, String message) {

private CompletionStage<String> getUserNameFromFacebook(String senderId) {
String url = "https://graph.facebook.com/v2.6/" + senderId +
"?fields=first_name,last_name&access_token=" + Configuration.facebookBotToken;
"?fields=first_name,last_name&access_token=" + Configuration.facebookBotToken;
WSRequest request = ws.url(url);


return request.get().thenApplyAsync(WSResponse::asJson)
.thenApplyAsync(name -> name.path("first_name").asText() + " " + name.path("last_name").asText());
.thenApplyAsync(name -> name.path("first_name").asText() + " " + name.path("last_name").asText());
}
}
111 changes: 56 additions & 55 deletions app/bots/TelegramBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,69 +16,70 @@
@Singleton
public class TelegramBot extends TelegramLongPollingBot implements Bot {

private BotFather botFather;

@Inject
public TelegramBot(BotFather botFather) {
this.botFather = botFather;
botFather.registerBot(Contract.TELEGRAM, this);
}
private BotFather botFather;

@Inject
public TelegramBot(BotFather botFather) {
this.botFather = botFather;
botFather.registerBot(Contract.TELEGRAM, this);
}

@Override
public void onUpdateReceived(Update update) {
try {
if(update.hasMessage()) {
Message telegramMessage = update.getMessage();
String text = telegramMessage.getText();
String senderId = telegramMessage.getFrom().getId().toString();
String senderFirstName = telegramMessage.getFrom().getFirstName();
String senderLastName = telegramMessage.getFrom().getLastName();
String name = senderFirstName + " " + senderLastName;
@Override
public void onUpdateReceived(Update update) {
try {
if (update.hasMessage()) {
Message telegramMessage = update.getMessage();
String text = telegramMessage.getText();
String senderId = telegramMessage.getFrom().getId().toString();
String senderFirstName = telegramMessage.getFrom().getFirstName();
String senderLastName = telegramMessage.getFrom().getLastName();
String name = senderFirstName + " " + senderLastName;

if(text.startsWith("+signup")) {
String userId = MessageParser.extractUserId(text);
if(userId != null && !userId.isEmpty() && senderFirstName != null && senderLastName != null) {
botFather.registerUser(new User(userId, name, Contract.TELEGRAM, senderId)).thenApplyAsync(dbMessage -> {
sendMessage(senderId, dbMessage);
return null;
});
}
} else {
checkAndSend(senderId, Contract.TELEGRAM, text, botFather.sendMessage);
}
}
} catch (Exception ex) {
Logger.error("Exception in onUpdateReceived()", ex);
if (text.startsWith("+signup")) {
String userId = MessageParser.extractUserId(text);
if (userId != null && !userId.isEmpty() && senderFirstName != null && senderLastName != null) {
botFather
.registerUser(new User(userId, name, Contract.TELEGRAM, senderId))
.thenApplyAsync(dbMessage -> {
sendMessage(senderId, dbMessage);
return null;
});
}
} else {
checkAndSend(senderId, Contract.TELEGRAM, text, botFather.sendMessage);
}
}
} catch (Exception ex) {
Logger.error("Exception in onUpdateReceived()", ex);
}
}

@Override
public String getBotUsername() {
return Configuration.telegramBotName;
}
@Override
public String getBotUsername() {
return Configuration.telegramBotName;
}

@Override
public String getBotToken() {
return Configuration.telegramBotToken;
}
@Override
public String getBotToken() {
return Configuration.telegramBotToken;
}

@Override
public String getName() {
return Contract.TELEGRAM;
}
@Override
public String getName() {
return Contract.TELEGRAM;
}

@Override
public void sendMessage(String recipientId, String message) {
SendMessage newMessage = new SendMessage();
newMessage.enableMarkdown(true);
newMessage.setChatId(recipientId);
Logger.info("ChatId: " + recipientId);
newMessage.setText(message);
try {
sendMessage(newMessage);
} catch (TelegramApiException t) {
Logger.error("TelegramApiException", t.getApiResponse());
}
@Override
public void sendMessage(String recipientId, String message) {
SendMessage newMessage = new SendMessage();
newMessage.enableMarkdown(true);
newMessage.setChatId(recipientId);
Logger.info("ChatId: " + recipientId);
newMessage.setText(message);
try {
sendMessage(newMessage);
} catch (TelegramApiException t) {
Logger.error("TelegramApiException", t.getApiResponse());
}
}
}
70 changes: 35 additions & 35 deletions app/controllers/BotController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,51 @@
import bots.FacebookBot;
import com.fasterxml.jackson.databind.JsonNode;
import play.Logger;
import play.mvc.*;
import play.mvc.Controller;
import play.mvc.Result;

import javax.inject.Inject;
import java.util.Map;

public class BotController extends Controller {

private final FacebookBot facebookBot;
private final FacebookBot facebookBot;

@Inject
public BotController(FacebookBot facebookBot) {
this.facebookBot = facebookBot;
}
@Inject
public BotController(FacebookBot facebookBot) {
this.facebookBot = facebookBot;
}

public Result index() {
return ok("Hello Bots!");
}
public Result index() {
return ok("Hello Bots!");
}

public Result facebookVerify() {
Map<String, String[]> queryString = request().queryString();

try {
String verifyToken = queryString.get("hub.verify_token")[0];
String challenge = queryString.get("hub.challenge")[0];
Logger.warn("Facebook Verified");

if (verifyToken.equals(Configuration.facebookBotVerification)) {
return ok(challenge);
}
return unauthorized("Error, wrong token");
} catch (Exception e) {
Logger.error("Exception verification, parameters are not suitable.", e);
return unauthorized("Error, missing parameters");
}
}
public Result facebookVerify() {
Map<String, String[]> queryString = request().queryString();

public Result receiveFacebookMessage() {
JsonNode json = request().body().asJson();
boolean isReceived = facebookBot.receive(json);
if(isReceived) {
return ok();
}
else {
return internalServerError();
}
try {
String verifyToken = queryString.get("hub.verify_token")[0];
String challenge = queryString.get("hub.challenge")[0];
Logger.warn("Facebook Verified");

if (verifyToken.equals(Configuration.facebookBotVerification)) {
return ok(challenge);
}
return unauthorized("Error, wrong token");
} catch (Exception e) {
Logger.error("Exception verification, parameters are not suitable.", e);
return unauthorized("Error, missing parameters");
}
}

public Result receiveFacebookMessage() {
JsonNode json = request().body().asJson();
boolean isReceived = facebookBot.receive(json);
if (isReceived) {
return ok();
} else {
return internalServerError();
}
}

}
18 changes: 9 additions & 9 deletions app/helpers/DBHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@
@Singleton
public class DBHelper {

// http://stackoverflow.com/a/18198349/3671697
@FunctionalInterface
private interface CheckedFunction<U> {
U apply(PreparedStatement p) throws SQLException;
}

private Database db;

@Inject
Expand All @@ -39,7 +33,7 @@ private <U> DBResult execute(String query, CheckedFunction<U> f) {
statement = connection.prepareStatement(query);
U u = f.apply(statement);
result = new DBSuccessResult<>(u);
} catch(MySQLIntegrityConstraintViolationException ex) {
} catch (MySQLIntegrityConstraintViolationException ex) {
int reason = Contract.DUPLICATE_ENTRY;
result = new DBFailureResult(reason);
} catch (SQLException ex) {
Expand All @@ -48,10 +42,10 @@ private <U> DBResult execute(String query, CheckedFunction<U> f) {
result = new DBFailureResult(reason);
} finally {
try {
if(statement != null) {
if (statement != null) {
statement.close();
}
if(connection != null) {
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
Expand Down Expand Up @@ -82,4 +76,10 @@ public CompletionStage<DBResult> getUser(String userId) {
return CompletableFuture.supplyAsync(() -> execute(query, queryDB));
}

// http://stackoverflow.com/a/18198349/3671697
@FunctionalInterface
private interface CheckedFunction<U> {
U apply(PreparedStatement p) throws SQLException;
}

}
2 changes: 1 addition & 1 deletion app/helpers/RedisHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public CompletionStage<User> getUser(String id) {
.thenApplyAsync(list -> {
Logger.info("Redis.getUser" + list);
try {
if(list.get(0) == null) {
if (list.get(0) == null) {
return null;
} else {
return new User(list);
Expand Down
22 changes: 11 additions & 11 deletions app/models/DBFailureResult.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@

public class DBFailureResult implements DBResult {

private int reason;
private int reason;

public DBFailureResult(int reason) {
this.reason = reason;
}
public DBFailureResult(int reason) {
this.reason = reason;
}

public int getReason() {
return reason;
}
public int getReason() {
return reason;
}

@Override
public boolean isSuccess() {
return false;
}
@Override
public boolean isSuccess() {
return false;
}
}
Loading

0 comments on commit 89229f8

Please sign in to comment.