Remove anonymous bot instantiation in ABs, refactor webhook functions

This commit is contained in:
Abbas Abou Daya 2018-06-04 04:47:21 -04:00
parent b5bfaced7e
commit e1e829151b
7 changed files with 112 additions and 147 deletions

View File

@ -6,8 +6,7 @@ import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.generics.LongPollingBot;
import java.util.List;
import org.telegram.telegrambots.util.WebhookUtils;
import static org.telegram.abilitybots.api.db.MapDBContext.onlineInstance;
@ -17,27 +16,8 @@ import static org.telegram.abilitybots.api.db.MapDBContext.onlineInstance;
* @author Abbas Abou Daya
*/
public abstract class AbilityBot extends BaseAbilityBot implements LongPollingBot {
private final TelegramLongPollingBot bot;
protected AbilityBot(String botToken, String botUsername, DBContext db, DefaultBotOptions botOptions) {
super(botToken, botUsername, db, botOptions);
bot = new TelegramLongPollingBot() {
@Override
public void onUpdateReceived(Update update) {
AbilityBot.this.onUpdateReceived(update);
}
@Override
public String getBotUsername() {
return botUsername;
}
@Override
public String getBotToken() {
return botToken;
}
};
}
protected AbilityBot(String botToken, String botUsername, DBContext db) {
@ -53,17 +33,12 @@ public abstract class AbilityBot extends BaseAbilityBot implements LongPollingBo
}
@Override
public void onUpdatesReceived(List<Update> updates) {
bot.onUpdatesReceived(updates);
public void onUpdateReceived(Update update) {
super.onUpdateReceived(update);
}
@Override
public void clearWebhook() throws TelegramApiRequestException {
bot.clearWebhook();
}
@Override
public void onClosing() {
bot.onClosing();
WebhookUtils.clearWebhook(this);
}
}

View File

@ -7,6 +7,7 @@ import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramWebhookBot;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.generics.WebhookBot;
import org.telegram.telegrambots.util.WebhookUtils;
import static org.telegram.abilitybots.api.db.MapDBContext.onlineInstance;
@ -16,34 +17,12 @@ import static org.telegram.abilitybots.api.db.MapDBContext.onlineInstance;
* @author Abbas Abou Daya
*/
public abstract class AbilityWebhookBot extends BaseAbilityBot implements WebhookBot {
private final TelegramWebhookBot bot;
private final String botPath;
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, DefaultBotOptions botOptions) {
super(botToken, botUsername, db, botOptions);
bot = new TelegramWebhookBot() {
@Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
AbilityWebhookBot.this.onUpdateReceived(update);
return null;
}
@Override
public String getBotUsername() {
return botUsername;
}
@Override
public String getBotToken() {
return botToken;
}
@Override
public String getBotPath() {
return botPath;
}
};
this.botPath = botPath;
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db) {
@ -60,16 +39,17 @@ public abstract class AbilityWebhookBot extends BaseAbilityBot implements Webhoo
@Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
return bot.onWebhookUpdateReceived(update);
super.onUpdateReceived(update);
return null;
}
@Override
public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException {
bot.setWebhook(url, publicCertificatePath);
WebhookUtils.setWebhook(this, url, publicCertificatePath);
}
@Override
public String getBotPath() {
return bot.getBotPath();
return botPath;
}
}

View File

@ -21,6 +21,7 @@ import org.telegram.telegrambots.api.methods.send.SendDocument;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;
@ -92,7 +93,7 @@ import static org.telegram.abilitybots.api.util.AbilityUtils.*;
*
* @author Abbas Abou Daya
*/
public abstract class BaseAbilityBot extends TelegramLongPollingBot {
public abstract class BaseAbilityBot extends DefaultAbsSender {
private static final String TAG = BaseAbilityBot.class.getSimpleName();
// DB objects
@ -191,7 +192,6 @@ public abstract class BaseAbilityBot extends TelegramLongPollingBot {
*
* @param update the update received by Telegram's API
*/
@Override
public void onUpdateReceived(Update update) {
BotLogger.info(format("New update [%s] received at %s", update.getUpdateId(), now()), format("%s - %s", TAG, botUsername));
BotLogger.info(update.toString(), TAG);
@ -216,12 +216,10 @@ public abstract class BaseAbilityBot extends TelegramLongPollingBot {
BotLogger.info(format("Processing of update [%s] ended at %s%n---> Processing time: [%d ms] <---%n", update.getUpdateId(), now(), processingTime), format("%s - %s", TAG, botUsername));
}
@Override
public String getBotToken() {
return botToken;
}
@Override
public String getBotUsername() {
return botUsername;
}

View File

@ -6,14 +6,11 @@ import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.util.EntityUtils;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.groupadministration.SetChatPhoto;
@ -39,7 +36,6 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.telegram.telegrambots.Constants.SOCKET_TIMEOUT;
@ -747,7 +743,7 @@ public abstract class DefaultAbsSender extends AbsSender {
return httppost;
}
protected String getBaseUrl() {
public String getBaseUrl() {
return options.getBaseUrl() + getBotToken() + "/";
}

View File

@ -1,10 +1,9 @@
package org.telegram.telegrambots.bots;
import org.telegram.telegrambots.ApiContext;
import org.telegram.telegrambots.api.methods.updates.DeleteWebhook;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.generics.LongPollingBot;
import org.telegram.telegrambots.util.WebhookUtils;
/**
* @author Ruben Bermudez
@ -23,19 +22,11 @@ public abstract class TelegramLongPollingBot extends DefaultAbsSender implements
@Override
public void clearWebhook() throws TelegramApiRequestException {
try {
boolean result = execute(new DeleteWebhook());
if (!result) {
throw new TelegramApiRequestException("Error removing old webhook");
}
} catch (TelegramApiException e) {
throw new TelegramApiRequestException("Error removing old webhook", e);
}
WebhookUtils.clearWebhook(this);
}
@Override
public void onClosing() {
exe.shutdown();
}
}

View File

@ -1,28 +1,9 @@
package org.telegram.telegrambots.bots;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.ApiConstants;
import org.telegram.telegrambots.ApiContext;
import org.telegram.telegrambots.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder;
import org.telegram.telegrambots.generics.WebhookBot;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.telegram.telegrambots.util.WebhookUtils;
/**
* @author Ruben Bermudez
@ -32,54 +13,16 @@ import java.nio.charset.StandardCharsets;
* @date 14 of January of 2016
*/
public abstract class TelegramWebhookBot extends DefaultAbsSender implements WebhookBot {
private final DefaultBotOptions botOptions;
public TelegramWebhookBot() {
this(ApiContext.getInstance(DefaultBotOptions.class));
}
public TelegramWebhookBot(DefaultBotOptions options) {
super(options);
this.botOptions = options;
}
@Override
public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException {
try (CloseableHttpClient httpclient = TelegramHttpClientBuilder.build(getOptions())) {
String requestUrl = getBaseUrl() + SetWebhook.PATH;
HttpPost httppost = new HttpPost(requestUrl);
httppost.setConfig(botOptions.getRequestConfig());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, url);
if (botOptions.getMaxWebhookConnections() != null) {
builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, botOptions.getMaxWebhookConnections().toString());
}
if (botOptions.getAllowedUpdates() != null) {
builder.addTextBody(SetWebhook.ALLOWEDUPDATES_FIELD, new JSONArray(botOptions.getMaxWebhookConnections()).toString());
}
if (publicCertificatePath != null) {
File certificate = new File(publicCertificatePath);
if (certificate.exists()) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, certificate, ContentType.TEXT_PLAIN, certificate.getName());
}
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(ApiConstants.RESPONSE_FIELD_OK)) {
throw new TelegramApiRequestException("Error setting webhook", jsonObject);
}
}
} catch (JSONException e) {
throw new TelegramApiRequestException("Error deserializing setWebhook method response", e);
} catch (IOException e) {
throw new TelegramApiRequestException("Error executing setWebook method", e);
}
WebhookUtils.setWebhook(this, url, publicCertificatePath);
}
}

View File

@ -0,0 +1,82 @@
package org.telegram.telegrambots.util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.ApiConstants;
import org.telegram.telegrambots.api.methods.updates.DeleteWebhook;
import org.telegram.telegrambots.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public final class WebhookUtils {
private WebhookUtils() {
}
public static void setWebhook(DefaultAbsSender bot, String url, String publicCertificatePath) throws TelegramApiRequestException {
DefaultBotOptions botOptions = bot.getOptions();
try (CloseableHttpClient httpclient = TelegramHttpClientBuilder.build(botOptions)) {
String requestUrl = bot.getBaseUrl() + SetWebhook.PATH;
HttpPost httppost = new HttpPost(requestUrl);
httppost.setConfig(botOptions.getRequestConfig());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, url);
if (botOptions.getMaxWebhookConnections() != null) {
builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, botOptions.getMaxWebhookConnections().toString());
}
if (botOptions.getAllowedUpdates() != null) {
builder.addTextBody(SetWebhook.ALLOWEDUPDATES_FIELD, new JSONArray(botOptions.getMaxWebhookConnections()).toString());
}
if (publicCertificatePath != null) {
File certificate = new File(publicCertificatePath);
if (certificate.exists()) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, certificate, ContentType.TEXT_PLAIN, certificate.getName());
}
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(ApiConstants.RESPONSE_FIELD_OK)) {
throw new TelegramApiRequestException("Error setting webhook", jsonObject);
}
}
} catch (JSONException e) {
throw new TelegramApiRequestException("Error deserializing setWebhook method response", e);
} catch (IOException e) {
throw new TelegramApiRequestException("Error executing setWebook method", e);
}
}
public static void clearWebhook(DefaultAbsSender bot) throws TelegramApiRequestException {
try {
boolean result = bot.execute(new DeleteWebhook());
if (!result) {
throw new TelegramApiRequestException("Error removing old webhook");
}
} catch (TelegramApiException e) {
throw new TelegramApiRequestException("Error removing old webhook", e);
}
}
}