diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..42f24ce --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +### Maven template +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +### Java template +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# unneeded files +.idea/dataSources.* +.idea/workspace.xml + +# logs files +*.log + +# Certs +*.jks +*.cer +*.pem \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml index f8ce7d9..47e81db 100644 --- a/.idea/dataSources.xml +++ b/.idea/dataSources.xml @@ -13,6 +13,7 @@ + \ No newline at end of file diff --git a/.idea/resourceBundles.xml b/.idea/resourceBundles.xml new file mode 100644 index 0000000..7267597 --- /dev/null +++ b/.idea/resourceBundles.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 62f9d18..c9ebe40 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,101 +2,35 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + @@ -140,39 +74,38 @@ - - + + - - + + - - + + - - + + + + + + + + - - + + - - - - - - - - - - + + + @@ -201,7 +134,7 @@ - + @@ -212,61 +145,62 @@ + true @@ -451,8 +385,6 @@ - - @@ -510,10 +442,6 @@ @@ -597,11 +525,37 @@ - + + - + + + + + + + + + + + + @@ -635,7 +589,7 @@ + + @@ -714,6 +684,7 @@ + @@ -728,11 +699,11 @@ + - @@ -1043,6 +1014,22 @@ + + + @@ -1317,30 +1304,20 @@ - - - 1434854005227 - - - 1434896932077 - - - 1434896979344 - - - 1434904623863 - 1434905289461 @@ -1600,11 +1577,47 @@ - - @@ -1616,7 +1629,7 @@ - + @@ -1625,29 +1638,29 @@ - + + - + + + + - - - - @@ -1693,12 +1706,6 @@ - - - - - - @@ -1718,7 +1725,14 @@ - @@ -1742,46 +1756,34 @@ @@ -1790,404 +1792,452 @@ - + - - + + + - + - - + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + - - - - - - + + - + - - + + + + + - + - - + + - + - - + + + + + - + - - + + + + + - + - - + + - + - - + + + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - + + - - - - + - - + + + - + - - + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + - + + - + - - + + - + - - - - - + + + - + - - + + - + - - + + - + - - - - - - - - - - - - - - - - - - + + + - + - - + + - + - - + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - - + + + - + - - + + + - + - - + + - + - - + + + - + - - + + + - + - - + + - + - + - + - - + + - - - - - - + + + + + + + + + + + + + diff --git a/src/main/java/org/telegram/BotConfig.java b/src/main/java/org/telegram/BotConfig.java index 7c0e841..9f56e8e 100644 --- a/src/main/java/org/telegram/BotConfig.java +++ b/src/main/java/org/telegram/BotConfig.java @@ -7,12 +7,16 @@ package org.telegram; * @date 20 of June of 2015 */ public class BotConfig { - public static final String TOKENWEATHER = ""; + public static final String TOKENWEATHER = ""; public static final String USERNAMEWEATHER = "weatherbot"; - public static final String TOKENTRANSIFEX = ""; + public static final String TOKENTRANSIFEX = ""; public static final String USERNAMETRANSIFEX = "TGlanguagesbot"; - public static final String TOKENFILES = ""; + public static final String TOKENFILES = ""; public static final String USERNAMEFILES = "filesbot"; - public static final String TOKENDIRECTIONS = ""; + public static final String TOKENDIRECTIONS = ""; public static final String USERNAMEDIRECTIONS = "directionsbot"; + public static final String TOKENCHANNEL = ""; + public static final String USERNAMECHANNEL = "channelupdatesbot"; + public static final String TOKENRAE = ""; + public static final String USERNAMERAE = "raebot"; } diff --git a/src/main/java/org/telegram/Main.java b/src/main/java/org/telegram/Main.java index a765cc3..0ecf15b 100644 --- a/src/main/java/org/telegram/Main.java +++ b/src/main/java/org/telegram/Main.java @@ -3,9 +3,6 @@ package org.telegram; import org.telegram.updateshandlers.*; import org.telegram.updatesreceivers.Webhook; -import java.util.logging.Level; -import java.util.logging.Logger; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,15 +21,16 @@ public class Main { initBots(); if (BuildVars.useWebHook) { - webhook.startDebugServer(); - //webhook.startServer(); + webhook.startServer(); } } private static void initBots() { UpdatesCallback weatherBot = new WeatherHandlers(webhook); + UpdatesCallback channelBot = new ChannelHandlers(webhook); UpdatesCallback transifexBot = new TransifexHandlers(webhook); UpdatesCallback filesBot = new FilesHandlers(webhook); UpdatesCallback directionsBot = new DirectionsHandlers(webhook); + UpdatesCallback raeBot = new RaeHandlers(webhook); } } diff --git a/src/main/java/org/telegram/SenderHelper.java b/src/main/java/org/telegram/SenderHelper.java index 841d1b4..06972de 100644 --- a/src/main/java/org/telegram/SenderHelper.java +++ b/src/main/java/org/telegram/SenderHelper.java @@ -16,7 +16,6 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONObject; -import org.telegram.api.objects.Message; import org.telegram.api.methods.*; import org.telegram.services.BotLogger; import org.telegram.updateshandlers.SentCallback; @@ -24,10 +23,8 @@ import org.telegram.updateshandlers.SentCallback; import java.io.File; import java.io.IOException; import java.io.InvalidObjectException; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -38,7 +35,7 @@ import java.util.concurrent.Executors; * @date 20 of June of 2015 */ public class SenderHelper { - private static volatile BotLogger log = BotLogger.getLogger(SenderHelper.class.getName()); + private static final String LOGTAG = "SENDERHELPER"; private static final ExecutorService exe = Executors.newSingleThreadExecutor(); public static void SendDocument(SendDocument sendDocument, String botToken) { @@ -49,7 +46,7 @@ public class SenderHelper { if (sendDocument.isNewDocument()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId().toString()); + builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId()); builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); if (sendDocument.getReplayMarkup() != null) { builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString()); @@ -61,7 +58,7 @@ public class SenderHelper { httppost.setEntity(multipart); } else { List nameValuePairs = new ArrayList<>(); - nameValuePairs.add(new BasicNameValuePair(SendDocument.CHATID_FIELD, sendDocument.getChatId().toString())); + nameValuePairs.add(new BasicNameValuePair(SendDocument.CHATID_FIELD, sendDocument.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendDocument.DOCUMENT_FIELD, sendDocument.getDocument())); if (sendDocument.getReplayMarkup() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toString())); @@ -73,12 +70,13 @@ public class SenderHelper { } CloseableHttpResponse response = httpClient.execute(httppost); + } catch (IOException e) { + BotLogger.error(LOGTAG, e); + } finally { if (sendDocument.isNewDocument()) { File fileToDelete = new File(sendDocument.getDocument()); fileToDelete.delete(); } - } catch (IOException e) { - log.error(e); } } @@ -90,7 +88,7 @@ public class SenderHelper { if (sendPhoto.isNewPhoto()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId().toString()); + builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()); builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); if (sendPhoto.getReplayMarkup() != null) { builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString()); @@ -105,7 +103,7 @@ public class SenderHelper { httppost.setEntity(multipart); } else { List nameValuePairs = new ArrayList<>(); - nameValuePairs.add(new BasicNameValuePair(SendPhoto.CHATID_FIELD, sendPhoto.getChatId().toString())); + nameValuePairs.add(new BasicNameValuePair(SendPhoto.CHATID_FIELD, sendPhoto.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendPhoto.PHOTO_FIELD, sendPhoto.getPhoto())); if (sendPhoto.getReplayMarkup() != null) { nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toString())); @@ -121,7 +119,7 @@ public class SenderHelper { CloseableHttpResponse response = httpClient.execute(httppost); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } @@ -133,7 +131,7 @@ public class SenderHelper { if (sendVideo.isNewVideo()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId().toString()); + builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId()); builder.addBinaryBody(SendVideo.VIDEO_FIELD, new File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); if (sendVideo.getReplayMarkup() != null) { builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString()); @@ -151,7 +149,7 @@ public class SenderHelper { httppost.setEntity(multipart); } else { List nameValuePairs = new ArrayList<>(); - nameValuePairs.add(new BasicNameValuePair(SendVideo.CHATID_FIELD, sendVideo.getChatId().toString())); + nameValuePairs.add(new BasicNameValuePair(SendVideo.CHATID_FIELD, sendVideo.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendVideo.VIDEO_FIELD, sendVideo.getVideo())); if (sendVideo.getReplayMarkup() != null) { nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toString())); @@ -170,7 +168,7 @@ public class SenderHelper { CloseableHttpResponse response = httpClient.execute(httppost); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } @@ -182,7 +180,7 @@ public class SenderHelper { if (sendSticker.isNewSticker()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId().toString()); + builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId()); builder.addBinaryBody(SendSticker.STICKER_FIELD, new File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); if (sendSticker.getReplayMarkup() != null) { builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString()); @@ -194,7 +192,7 @@ public class SenderHelper { httppost.setEntity(multipart); } else { List nameValuePairs = new ArrayList<>(); - nameValuePairs.add(new BasicNameValuePair(SendSticker.CHATID_FIELD, sendSticker.getChatId().toString())); + nameValuePairs.add(new BasicNameValuePair(SendSticker.CHATID_FIELD, sendSticker.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendSticker.STICKER_FIELD, sendSticker.getSticker())); if (sendSticker.getReplayMarkup() != null) { nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toString())); @@ -206,14 +204,14 @@ public class SenderHelper { } CloseableHttpResponse response = httpClient.execute(httppost); + } catch (IOException e) { + BotLogger.error(LOGTAG, e); + } finally { if (sendSticker.isNewSticker()) { File fileToDelete = new File(sendSticker.getSticker()); fileToDelete.delete(); } - } catch (IOException e) { - log.error(e); } - } public static void SendWebhook(String webHookURL, String botToken) { @@ -233,14 +231,15 @@ public class SenderHelper { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseContent = EntityUtils.toString(buf, "UTF-8"); - log.debug(responseContent); + BotLogger.debug(LOGTAG, responseContent); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } - public static void SendApiMethod(BotApiMethod method, String botToken) { + public static void SendApiMethod(BotApiMethod method, String botToken) throws InvalidObjectException { + String responseContent = "{}"; try { CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); String url = Constants.BASEURL + botToken + "/" + method.getPath(); @@ -250,15 +249,16 @@ public class SenderHelper { CloseableHttpResponse response = httpclient.execute(httppost); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); - String responseContent = EntityUtils.toString(buf, "UTF-8"); - - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean("ok")) { - throw new InvalidObjectException(jsonObject.toString()); - } + responseContent = EntityUtils.toString(buf, "UTF-8"); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } + + JSONObject jsonObject = new JSONObject(responseContent); + if (!jsonObject.getBoolean("ok")) { + throw new InvalidObjectException(jsonObject.getString("description")); + } + } public static void SendApiMethodAsync(BotApiMethod method, String botToken, SentCallback callback) { @@ -280,7 +280,7 @@ public class SenderHelper { } callback.onResult(method, jsonObject); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } }); } diff --git a/src/main/java/org/telegram/api/methods/AnswerInlineQuery.java b/src/main/java/org/telegram/api/methods/AnswerInlineQuery.java new file mode 100644 index 0000000..21071fb --- /dev/null +++ b/src/main/java/org/telegram/api/methods/AnswerInlineQuery.java @@ -0,0 +1,138 @@ +package org.telegram.api.methods; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONArray; +import org.json.JSONObject; +import org.telegram.api.objects.InlineQueryResult; + +import java.io.IOException; +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Use this method to send answers to an inline query. On success, True is returned. + * @date 01 of January of 2016 + */ +public class AnswerInlineQuery extends BotApiMethod { + public static final String PATH = "answerInlineQuery"; + + public static final String INLINEQUERYID_FIELD = "inline_query_id"; + private String inlineQueryId; ///< Unique identifier for answered query + public static final String RESULTS_FIELD = "results"; + private List results; ///< A JSON-serialized array of results for the inline query + public static final String CACHETIME_FIELD = "cache_time"; + private Integer cacheTime; ///< Optional The maximum amount of time the result of the inline query may be cached on the server + public static final String ISPERSONAL_FIELD = "is_personal"; + private Boolean isPersonal; ///< Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query + public static final String NEXTOFFSET_FIELD = "next_offset"; + private String nextOffset; ///< Optional Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. + + public AnswerInlineQuery() { + super(); + } + + public String getInlineQueryId() { + return inlineQueryId; + } + + public void setInlineQueryId(String inlineQueryId) { + this.inlineQueryId = inlineQueryId; + } + + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } + + public Integer getCacheTime() { + return cacheTime; + } + + public void setCacheTime(Integer cacheTime) { + this.cacheTime = cacheTime; + } + + public Boolean getPersonal() { + return isPersonal; + } + + public void setPersonal(Boolean personal) { + isPersonal = personal; + } + + public String getNextOffset() { + return nextOffset; + } + + public void setNextOffset(String nextOffset) { + this.nextOffset = nextOffset; + } + + @Override + public JSONObject toJson() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put(INLINEQUERYID_FIELD, inlineQueryId); + JSONArray JSONResults = new JSONArray(); + for (InlineQueryResult result: results) { + JSONResults.put(result.toJson()); + } + jsonObject.put(RESULTS_FIELD, JSONResults); + if (cacheTime != null) { + jsonObject.put(CACHETIME_FIELD, cacheTime); + } + if (isPersonal != null) { + jsonObject.put(ISPERSONAL_FIELD, isPersonal); + } + if (nextOffset != null) { + jsonObject.put(NEXTOFFSET_FIELD, nextOffset); + } + return jsonObject; + } + + @Override + public String getPath() { + return PATH; + } + + @Override + public Boolean deserializeResponse(JSONObject answer) { + if (answer.getBoolean("ok")) { + return answer.getBoolean("result"); + } + return null; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(METHOD_FIELD, PATH); + gen.writeArrayFieldStart(RESULTS_FIELD); + for (InlineQueryResult result: results) { + gen.writeObject(result); + } + gen.writeEndArray(); + if (cacheTime != null) { + gen.writeNumberField(CACHETIME_FIELD, cacheTime); + } + if (isPersonal != null) { + gen.writeBooleanField(ISPERSONAL_FIELD, isPersonal); + } + if (nextOffset != null) { + gen.writeStringField(NEXTOFFSET_FIELD, nextOffset); + } + + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/methods/ForwardMessage.java b/src/main/java/org/telegram/api/methods/ForwardMessage.java index 714afe8..11a41f1 100644 --- a/src/main/java/org/telegram/api/methods/ForwardMessage.java +++ b/src/main/java/org/telegram/api/methods/ForwardMessage.java @@ -18,7 +18,7 @@ public class ForwardMessage extends BotApiMethod { public static final String PATH = "forwardmessage"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels) public static final String FROMCHATID_FIELD = "from_chat_id"; private Integer fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id public static final String MESSAGEID_FIELD = "message_id"; @@ -28,11 +28,11 @@ public class ForwardMessage extends BotApiMethod { super(); } - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } @@ -56,7 +56,7 @@ public class ForwardMessage extends BotApiMethod { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(CHATID_FIELD, chatId); + gen.writeStringField(CHATID_FIELD, chatId); gen.writeNumberField(FROMCHATID_FIELD, fromChatId); gen.writeNumberField(MESSAGEID_FIELD, messageId); gen.writeEndObject(); @@ -65,13 +65,7 @@ public class ForwardMessage extends BotApiMethod { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(CHATID_FIELD, chatId); - gen.writeNumberField(FROMCHATID_FIELD, fromChatId); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/api/methods/GetFile.java b/src/main/java/org/telegram/api/methods/GetFile.java index 7c1e705..2f49040 100644 --- a/src/main/java/org/telegram/api/methods/GetFile.java +++ b/src/main/java/org/telegram/api/methods/GetFile.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import org.json.JSONObject; import org.telegram.api.objects.File; -import org.telegram.api.objects.Message; import java.io.IOException; @@ -50,11 +49,7 @@ public class GetFile extends BotApiMethod { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/api/methods/GetMe.java b/src/main/java/org/telegram/api/methods/GetMe.java index a925df1..601686e 100644 --- a/src/main/java/org/telegram/api/methods/GetMe.java +++ b/src/main/java/org/telegram/api/methods/GetMe.java @@ -45,8 +45,6 @@ public class GetMe extends BotApiMethod { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeEndObject(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/methods/GetUserProfilePhotos.java b/src/main/java/org/telegram/api/methods/GetUserProfilePhotos.java index 161bdfe..90c032b 100644 --- a/src/main/java/org/telegram/api/methods/GetUserProfilePhotos.java +++ b/src/main/java/org/telegram/api/methods/GetUserProfilePhotos.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import org.json.JSONObject; -import org.telegram.api.objects.Message; import org.telegram.api.objects.UserProfilePhotos; import java.io.IOException; @@ -98,14 +97,6 @@ public class GetUserProfilePhotos extends BotApiMethod { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(USERID_FIELD, userId); - gen.writeNumberField(OFFSET_FIELD, offset); - if (limit != null) { - gen.writeNumberField(LIMIT_FIELD, limit); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/methods/SendAudio.java b/src/main/java/org/telegram/api/methods/SendAudio.java index 19fbb53..045dbf9 100644 --- a/src/main/java/org/telegram/api/methods/SendAudio.java +++ b/src/main/java/org/telegram/api/methods/SendAudio.java @@ -21,7 +21,7 @@ public class SendAudio { public static final String PATH = "sendaudio"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (or Username fro channels) public static final String AUDIO_FIELD = "audio"; private String audio; ///< Audio file to send. file_id as String to resend an audio that is already on the Telegram servers public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; @@ -39,11 +39,11 @@ public class SendAudio { super(); } - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } diff --git a/src/main/java/org/telegram/api/methods/SendChatAction.java b/src/main/java/org/telegram/api/methods/SendChatAction.java index d5b11fc..f170000 100644 --- a/src/main/java/org/telegram/api/methods/SendChatAction.java +++ b/src/main/java/org/telegram/api/methods/SendChatAction.java @@ -20,7 +20,7 @@ public class SendChatAction extends BotApiMethod{ public static final String PATH = "sendChatAction"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public static final String ACTION_FIELD = "action"; /** * Type of action to broadcast. @@ -34,11 +34,11 @@ public class SendChatAction extends BotApiMethod{ */ private String action; - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } @@ -74,16 +74,13 @@ public class SendChatAction extends BotApiMethod{ @Override public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); - gen.writeNumberField(CHATID_FIELD, chatId); + gen.writeStringField(CHATID_FIELD, chatId); gen.writeStringField(ACTION_FIELD, action); gen.writeEndObject(); } @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(CHATID_FIELD, chatId); - gen.writeStringField(ACTION_FIELD, action); - gen.writeEndObject(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/methods/SendDocument.java b/src/main/java/org/telegram/api/methods/SendDocument.java index 8e5a959..0345d66 100644 --- a/src/main/java/org/telegram/api/methods/SendDocument.java +++ b/src/main/java/org/telegram/api/methods/SendDocument.java @@ -12,7 +12,7 @@ public class SendDocument { public static final String PATH = "senddocument"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to or Username for the channel to send the message to public static final String DOCUMENT_FIELD = "document"; private String document; ///< File file to send. file_id as String to resend a file that is already on the Telegram servers public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; @@ -27,11 +27,11 @@ public class SendDocument { super(); } - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } diff --git a/src/main/java/org/telegram/api/methods/SendLocation.java b/src/main/java/org/telegram/api/methods/SendLocation.java index 5f1b7da..9e04b37 100644 --- a/src/main/java/org/telegram/api/methods/SendLocation.java +++ b/src/main/java/org/telegram/api/methods/SendLocation.java @@ -19,7 +19,7 @@ public class SendLocation extends BotApiMethod { public static final String PATH = "sendlocation"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public static final String LATITUDE_FIELD = "latitude"; private Float latitude; ///< Latitude of location public static final String LONGITUDE_FIELD = "longitude"; @@ -29,11 +29,11 @@ public class SendLocation extends BotApiMethod { public static final String REPLYMARKUP_FIELD = "reply_markup"; private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } @@ -85,7 +85,6 @@ public class SendLocation extends BotApiMethod { @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); jsonObject.put(LATITUDE_FIELD, latitude); jsonObject.put(LONGITUDE_FIELD, longitude); @@ -103,7 +102,7 @@ public class SendLocation extends BotApiMethod { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(CHATID_FIELD, chatId); + gen.writeStringField(CHATID_FIELD, chatId); gen.writeNumberField(LATITUDE_FIELD, latitude); gen.writeNumberField(LONGITUDE_FIELD, longitude); if (replayToMessageId != null) { @@ -119,19 +118,6 @@ public class SendLocation extends BotApiMethod { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(CHATID_FIELD, chatId); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); - } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); - } - - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/methods/SendMessage.java b/src/main/java/org/telegram/api/methods/SendMessage.java index 907dfa4..3a4741e 100644 --- a/src/main/java/org/telegram/api/methods/SendMessage.java +++ b/src/main/java/org/telegram/api/methods/SendMessage.java @@ -19,7 +19,7 @@ public class SendMessage extends BotApiMethod { public static final String PATH = "sendmessage"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public static final String TEXT_FIELD = "text"; private String text; ///< Text of the message to be sent public static final String PARSEMODE_FIELD = "parse_mode"; @@ -35,11 +35,11 @@ public class SendMessage extends BotApiMethod { super(); } - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } @@ -86,7 +86,6 @@ public class SendMessage extends BotApiMethod { @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); jsonObject.put(TEXT_FIELD, text); if (parseMode != null) { @@ -122,7 +121,7 @@ public class SendMessage extends BotApiMethod { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(CHATID_FIELD, chatId); + gen.writeStringField(CHATID_FIELD, chatId); gen.writeStringField(TEXT_FIELD, text); if (parseMode != null) { @@ -144,25 +143,6 @@ public class SendMessage extends BotApiMethod { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(CHATID_FIELD, chatId); - gen.writeStringField(TEXT_FIELD, text); - - if (parseMode != null) { - gen.writeStringField(PARSEMODE_FIELD, parseMode); - } - if (disableWebPagePreview != null) { - gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, disableWebPagePreview); - } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); - } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); - } - - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/methods/SendPhoto.java b/src/main/java/org/telegram/api/methods/SendPhoto.java index 06adc91..af128a9 100644 --- a/src/main/java/org/telegram/api/methods/SendPhoto.java +++ b/src/main/java/org/telegram/api/methods/SendPhoto.java @@ -12,7 +12,7 @@ public class SendPhoto { public static final String PATH = "sendphoto"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public static final String PHOTO_FIELD = "photo"; private String photo; ///< Photo to send. file_id as String to resend a photo that is already on the Telegram servers public static final String CAPTION_FIELD = "photo"; @@ -30,11 +30,11 @@ public class SendPhoto { super(); } - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } diff --git a/src/main/java/org/telegram/api/methods/SendSticker.java b/src/main/java/org/telegram/api/methods/SendSticker.java index 77d7f39..5e9ed96 100644 --- a/src/main/java/org/telegram/api/methods/SendSticker.java +++ b/src/main/java/org/telegram/api/methods/SendSticker.java @@ -12,7 +12,7 @@ public class SendSticker { public static final String PATH = "sendsticker"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public static final String STICKER_FIELD = "sticker"; private String sticker; ///< Sticker file to send. file_id as String to resend a sticker that is already on the Telegram servers public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; @@ -27,11 +27,11 @@ public class SendSticker { super(); } - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } diff --git a/src/main/java/org/telegram/api/methods/SendVideo.java b/src/main/java/org/telegram/api/methods/SendVideo.java index 98b7593..02dbd77 100644 --- a/src/main/java/org/telegram/api/methods/SendVideo.java +++ b/src/main/java/org/telegram/api/methods/SendVideo.java @@ -14,7 +14,7 @@ public class SendVideo { public static final String PATH = "sendvideo"; public static final String CHATID_FIELD = "chat_id"; - private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id + private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public static final String VIDEO_FIELD = "video"; private String video; ///< Video to send. file_id as String to resend a video that is already on the Telegram servers public static final String DURATION_FIELD = "duration"; @@ -33,11 +33,11 @@ public class SendVideo { super(); } - public Integer getChatId() { + public String getChatId() { return chatId; } - public void setChatId(Integer chatId) { + public void setChatId(String chatId) { this.chatId = chatId; } diff --git a/src/main/java/org/telegram/api/objects/Audio.java b/src/main/java/org/telegram/api/objects/Audio.java index 54fa19a..5ca8ec7 100644 --- a/src/main/java/org/telegram/api/objects/Audio.java +++ b/src/main/java/org/telegram/api/objects/Audio.java @@ -129,22 +129,6 @@ public class Audio implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(DURATION_FIELD, duration); - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, title); - } - if (performer != null) { - gen.writeStringField(PERFORMER_FIELD, performer); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/Chat.java b/src/main/java/org/telegram/api/objects/Chat.java index 7e2e6a2..68acd0c 100644 --- a/src/main/java/org/telegram/api/objects/Chat.java +++ b/src/main/java/org/telegram/api/objects/Chat.java @@ -16,22 +16,29 @@ import java.io.IOException; * @date 24 of June of 2015 */ public class Chat implements BotApiObject { + private static final String USERCHATTYPE = "private"; + private static final String GROUPCHATTYPE = "group"; + private static final String CHANNELCHATTYPE = "channel"; + private static final String SUPERGROUPCHATTYPE = "supergroup"; public static final String ID_FIELD = "id"; @JsonProperty(ID_FIELD) - private Integer id; ///< Unique identifier for this chat + private Long id; ///< Unique identifier for this chat, not exciding 1e13 by absolute value + public static final String TYPE_FIELD = "type"; + @JsonProperty(TYPE_FIELD) + private String type; ///< Type of the chat, one of “private”, “group” or “channel” public static final String TITLE_FIELD = "title"; @JsonProperty(TITLE_FIELD) - private String title; ///< Group name + private String title; ///< Optional. Title of the chat, only for channels and group chat public static final String FIRSTNAME_FIELD = "first_name"; @JsonProperty(FIRSTNAME_FIELD) - private String firstName; ///< User‘s or bot’s first name + private String firstName; ///< Optional. Username of the chat, only for private chats and channels if available public static final String LASTNAME_FIELD = "last_name"; @JsonProperty(LASTNAME_FIELD) - private String lastName; ///< Optional. User‘s or bot’s last name + private String lastName; ///< Optional. Interlocutor's first name for private chats public static final String USERNAME_FIELD = "username"; @JsonProperty(USERNAME_FIELD) - private String userName; ///< Optional. User‘s or bot’s username + private String userName; ///< Optional. Interlocutor's last name for private chats public Chat() { super(); @@ -39,30 +46,40 @@ public class Chat implements BotApiObject { public Chat(JSONObject jsonObject) { super(); - this.id = jsonObject.getInt(ID_FIELD); - if (this.id > 0) { - this.firstName = jsonObject.getString(FIRSTNAME_FIELD); - if (jsonObject.has(LASTNAME_FIELD)) { - this.lastName = jsonObject.getString(LASTNAME_FIELD); - } - if (jsonObject.has(USERNAME_FIELD)) { - this.userName = jsonObject.getString(USERNAME_FIELD); - } - } else { + this.id = jsonObject.getLong(ID_FIELD); + this.type = jsonObject.getString(TYPE_FIELD); + if (jsonObject.has(TITLE_FIELD)) { this.title = jsonObject.getString(TITLE_FIELD); } + if (jsonObject.has(FIRSTNAME_FIELD)) { + this.firstName = jsonObject.getString(FIRSTNAME_FIELD); + } + if (jsonObject.has(LASTNAME_FIELD)) { + this.lastName = jsonObject.getString(LASTNAME_FIELD); + } + if (jsonObject.has(USERNAME_FIELD)) { + this.userName = jsonObject.getString(USERNAME_FIELD); + } } - public Integer getId() { + public Long getId() { return id; } public Boolean isGroupChat() { - if (id < 0) { - return true; - } else { - return false; - } + return GROUPCHATTYPE.equals(type); + } + + public Boolean isChannelChat() { + return CHANNELCHATTYPE.equals(type); + } + + public Boolean isUserChat() { + return USERCHATTYPE.equals(type); + } + + public Boolean isSuperGroupChat() { + return SUPERGROUPCHATTYPE.equals(type); } public String getTitle() { @@ -85,12 +102,21 @@ public class Chat implements BotApiObject { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeNumberField(ID_FIELD, id); - if (id > 0) { - gen.writeStringField(FIRSTNAME_FIELD, firstName); - gen.writeStringField(LASTNAME_FIELD, lastName); - gen.writeStringField(USERNAME_FIELD, userName); + gen.writeStringField(TYPE_FIELD, type); + if (isUserChat()) { + if (firstName != null) { + gen.writeStringField(FIRSTNAME_FIELD, firstName); + } + if (lastName != null) { + gen.writeStringField(LASTNAME_FIELD, lastName); + } } else { - gen.writeStringField(TITLE_FIELD, title); + if (title != null) { + gen.writeStringField(TITLE_FIELD, title); + } + } + if (!isGroupChat() && userName != null) { + gen.writeStringField(USERNAME_FIELD, userName); } gen.writeEndObject(); gen.flush(); @@ -98,16 +124,6 @@ public class Chat implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(ID_FIELD, id); - if (id > 0) { - gen.writeStringField(FIRSTNAME_FIELD, firstName); - gen.writeStringField(LASTNAME_FIELD, lastName); - gen.writeStringField(USERNAME_FIELD, userName); - } else { - gen.writeStringField(TITLE_FIELD, title); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/ChosenInlineQuery.java b/src/main/java/org/telegram/api/objects/ChosenInlineQuery.java new file mode 100644 index 0000000..c7d7d66 --- /dev/null +++ b/src/main/java/org/telegram/api/objects/ChosenInlineQuery.java @@ -0,0 +1,66 @@ +package org.telegram.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONObject; +import org.telegram.api.interfaces.BotApiObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief This object represents a result of an inline query that was chosen by the user and sent to their chat partner. + * @date 01 of January of 2016 + */ +public class ChosenInlineQuery implements BotApiObject { + public static final String RESULTID_FIELD = "id"; + @JsonProperty(RESULTID_FIELD) + private String resultId; ///< The unique identifier for the result that was chosen. + public static final String FROM_FIELD = "from"; + @JsonProperty(FROM_FIELD) + private User from; ///< The user that chose the result. + public static final String QUERY_FIELD = "query"; + @JsonProperty(QUERY_FIELD) + private String query; ///< The query that was used to obtain the result. + + public ChosenInlineQuery() { + super(); + } + + public ChosenInlineQuery(JSONObject jsonObject) { + super(); + this.resultId = jsonObject.getString(RESULTID_FIELD); + this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); + this.query = jsonObject.getString(QUERY_FIELD); + } + + public String getResultId() { + return resultId; + } + + public User getFrom() { + return from; + } + + public String getQuery() { + return query; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(RESULTID_FIELD, resultId); + gen.writeObjectField(FROM_FIELD, from); + gen.writeStringField(QUERY_FIELD, query); + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/objects/Contact.java b/src/main/java/org/telegram/api/objects/Contact.java index 7c0b4d0..499fbbe 100644 --- a/src/main/java/org/telegram/api/objects/Contact.java +++ b/src/main/java/org/telegram/api/objects/Contact.java @@ -63,16 +63,6 @@ public class Contact implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(PHONENUMBER_FIELD, phoneNumber); - gen.writeStringField(FIRSTNAME_FIELD, firstName); - if (lastName != null) { - gen.writeStringField(LASTNAME_FIELD, lastName); - } - if (userID != null) { - gen.writeNumberField(USERID_FIELD, userID); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/Document.java b/src/main/java/org/telegram/api/objects/Document.java index c6d0af1..e46242d 100644 --- a/src/main/java/org/telegram/api/objects/Document.java +++ b/src/main/java/org/telegram/api/objects/Document.java @@ -114,19 +114,6 @@ public class Document implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeObjectField(THUMB_FIELD, thumb); - if (fileName != null) { - gen.writeStringField(FILENAME_FIELD, fileName); - } - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/File.java b/src/main/java/org/telegram/api/objects/File.java index 1f20cc1..1715aec 100644 --- a/src/main/java/org/telegram/api/objects/File.java +++ b/src/main/java/org/telegram/api/objects/File.java @@ -81,15 +81,6 @@ public class File implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILE_ID, fileId); - if (fileSize != null) { - gen.writeNumberField(FILE_SIZE_FIELD, fileSize); - } - if (filePath != null) { - gen.writeStringField(FILE_PATH_FIELD, filePath); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/ForceReplyKeyboard.java b/src/main/java/org/telegram/api/objects/ForceReplyKeyboard.java index d7c41e5..18ede01 100644 --- a/src/main/java/org/telegram/api/objects/ForceReplyKeyboard.java +++ b/src/main/java/org/telegram/api/objects/ForceReplyKeyboard.java @@ -89,10 +89,6 @@ public class ForceReplyKeyboard implements ReplyKeyboard { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeBooleanField(FORCEREPLY_FIELD, forceReply); - gen.writeBooleanField(SELECTIVE_FIELD, selective); - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/InlineQuery.java b/src/main/java/org/telegram/api/objects/InlineQuery.java new file mode 100644 index 0000000..0a6f3a4 --- /dev/null +++ b/src/main/java/org/telegram/api/objects/InlineQuery.java @@ -0,0 +1,76 @@ +package org.telegram.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONObject; +import org.telegram.api.interfaces.BotApiObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief This object represents an incoming inline query. + * When the user sends an empty query, your bot could return some default or trending results. + * @date 01 of January of 2016 + */ +public class InlineQuery implements BotApiObject { + public static final String ID_FIELD = "id"; + @JsonProperty(ID_FIELD) + private String id; ///< Unique identifier for this query + public static final String FROM_FIELD = "from"; + @JsonProperty(FROM_FIELD) + private User from; ///< Sender + public static final String QUERY_FIELD = "query"; + @JsonProperty(QUERY_FIELD) + private String query; ///< Text of the query + public static final String OFFSET_FIELD = "offset"; + @JsonProperty(OFFSET_FIELD) + private String offset; ///< Offset of the results to be returned, can be controlled by the bot + + public InlineQuery() { + super(); + } + + public InlineQuery(JSONObject jsonObject) { + super(); + this.id = jsonObject.getString(ID_FIELD); + this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); + this.query = jsonObject.getString(QUERY_FIELD); + this.offset = jsonObject.getString(OFFSET_FIELD); + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(ID_FIELD, id); + gen.writeObjectField(FROM_FIELD, from); + gen.writeStringField(QUERY_FIELD, query); + gen.writeStringField(OFFSET_FIELD, offset); + gen.writeEndObject(); + gen.flush(); + } + + public String getId() { + return id; + } + + public User getFrom() { + return from; + } + + public String getQuery() { + return query; + } + + public String getOffset() { + return offset; + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/objects/InlineQueryResult.java b/src/main/java/org/telegram/api/objects/InlineQueryResult.java new file mode 100644 index 0000000..8040a19 --- /dev/null +++ b/src/main/java/org/telegram/api/objects/InlineQueryResult.java @@ -0,0 +1,13 @@ +package org.telegram.api.objects; + +import org.telegram.api.interfaces.BotApiObject; +import org.telegram.api.interfaces.IToJson; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief This object represents one result of an inline query. + * @date 01 of January of 2016 + */ +public interface InlineQueryResult extends BotApiObject, IToJson { +} diff --git a/src/main/java/org/telegram/api/objects/InlineQueryResultArticle.java b/src/main/java/org/telegram/api/objects/InlineQueryResultArticle.java new file mode 100644 index 0000000..b14b148 --- /dev/null +++ b/src/main/java/org/telegram/api/objects/InlineQueryResultArticle.java @@ -0,0 +1,233 @@ +package org.telegram.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Represents a link to an article or web page. + * @date 01 of January of 2016 + */ +public class InlineQueryResultArticle implements InlineQueryResult { + + public static final String TYPE_FIELD = "type"; + @JsonProperty(TYPE_FIELD) + private final String type = "article"; ///< Type of the result, must be “article” + public static final String ID_FIELD = "id"; + @JsonProperty(ID_FIELD) + private String id; ///< Unique identifier of this result + public static final String TITLE_FIELD = "title"; + @JsonProperty(TITLE_FIELD) + private String title; ///< Title of the result + public static final String MESSAGETEXT_FIELD = "message_text"; + @JsonProperty(MESSAGETEXT_FIELD) + private String messageText; ///< Text of a message to be sent + public static final String PARSEMODE_FIELD = "parse_mode"; + @JsonProperty(PARSEMODE_FIELD) + private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. + public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; + @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) + private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message + public static final String URL_FIELD = "url"; + @JsonProperty(URL_FIELD) + private String url; ///< Optional. URL of the result + public static final String HIDEURL_FIELD = "hide_url"; + @JsonProperty(HIDEURL_FIELD) + private Boolean hideUrl; ///< Optional. Pass True, if you don't want the URL to be shown in the message + public static final String DESCRIPTION_FIELD = "description"; + @JsonProperty(DESCRIPTION_FIELD) + private String description; ///< Optional. Short description of the result + public static final String THUMBURL_FIELD = "thumb_url"; + @JsonProperty(THUMBURL_FIELD) + private String thumbUrl; ///< Optional. Url of the thumbnail for the result + public static final String THUMBWIDTH_FIELD = "thumb_width"; + @JsonProperty(THUMBWIDTH_FIELD) + private Integer thumbWidth; ///< Optional. Thumbnail width + public static final String THUMBHEIGHT_FIELD = "thumb_height"; + @JsonProperty(THUMBHEIGHT_FIELD) + private Integer thumbHeight; ///< Optional. Thumbnail height + + public String getType() { + return type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getMessageText() { + return messageText; + } + + public void setMessageText(String messageText) { + this.messageText = messageText; + } + + public String getParseMode() { + return parseMode; + } + + public void setParseMode(String parseMode) { + this.parseMode = parseMode; + } + + public void setMarkdown(boolean enabled) { + if (enabled) { + parseMode = "Markdown"; + } else { + parseMode = null; + } + } + + public Boolean getDisableWebPagePreview() { + return disableWebPagePreview; + } + + public void setDisableWebPagePreview(Boolean disableWebPagePreview) { + this.disableWebPagePreview = disableWebPagePreview; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Boolean getHideUrl() { + return hideUrl; + } + + public void setHideUrl(Boolean hideUrl) { + this.hideUrl = hideUrl; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public Integer getThumbWidth() { + return thumbWidth; + } + + public void setThumbWidth(Integer thumbWidth) { + this.thumbWidth = thumbWidth; + } + + public Integer getThumbHeight() { + return thumbHeight; + } + + public void setThumbHeight(Integer thumbHeight) { + this.thumbHeight = thumbHeight; + } + + @Override + public JSONObject toJson() { + JSONObject jsonObject = new JSONObject(); + + jsonObject.put(TYPE_FIELD, this.type); + jsonObject.put(ID_FIELD, this.id); + jsonObject.put(TITLE_FIELD, this.title); + jsonObject.put(MESSAGETEXT_FIELD, this.messageText); + if (parseMode != null) { + jsonObject.put(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (url != null) { + jsonObject.put(URL_FIELD, this.url); + } + if (hideUrl != null) { + jsonObject.put(HIDEURL_FIELD, this.hideUrl); + } + if (description != null) { + jsonObject.put(DESCRIPTION_FIELD, this.description); + } + if (thumbUrl != null) { + jsonObject.put(THUMBURL_FIELD, this.thumbUrl); + } + if (thumbWidth != null) { + jsonObject.put(THUMBWIDTH_FIELD, this.thumbWidth); + } + if (thumbHeight != null) { + jsonObject.put(THUMBHEIGHT_FIELD, this.thumbHeight); + } + + return jsonObject; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(TYPE_FIELD, type); + gen.writeStringField(ID_FIELD, id); + gen.writeStringField(TITLE_FIELD, title); + gen.writeStringField(MESSAGETEXT_FIELD, messageText); + + if (parseMode != null) { + gen.writeStringField(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (url != null) { + gen.writeStringField(URL_FIELD, this.url); + } + if (hideUrl != null) { + gen.writeBooleanField(HIDEURL_FIELD, this.hideUrl); + } + if (description != null) { + gen.writeStringField(DESCRIPTION_FIELD, this.description); + } + if (thumbUrl != null) { + gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); + } + if (thumbWidth != null) { + gen.writeNumberField(THUMBWIDTH_FIELD, this.thumbWidth); + } + if (thumbHeight != null) { + gen.writeNumberField(THUMBHEIGHT_FIELD, this.thumbHeight); + } + + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/objects/InlineQueryResultGif.java b/src/main/java/org/telegram/api/objects/InlineQueryResultGif.java new file mode 100644 index 0000000..af3a82d --- /dev/null +++ b/src/main/java/org/telegram/api/objects/InlineQueryResultGif.java @@ -0,0 +1,213 @@ +package org.telegram.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. + * Alternatively, you can provide message_text to send it instead of the animation. + * @date 01 of January of 2016 + */ +public class InlineQueryResultGif implements InlineQueryResult { + + public static final String TYPE_FIELD = "type"; + @JsonProperty(TYPE_FIELD) + private final String type = "gif"; ///< Type of the result, must be "gif" + public static final String ID_FIELD = "id"; + @JsonProperty(ID_FIELD) + private String id; ///< Unique identifier of this result + public static final String GIFURL_FIELD = "gif_url"; + @JsonProperty(GIFURL_FIELD) + private String gifUrl; ///< A valid URL for the GIF file. File size must not exceed 1MB + public static final String GIFWIDTH_FIELD = "gif_width"; + @JsonProperty(GIFWIDTH_FIELD) + private Integer gifWidth; ///< Optional. Width of the GIF + public static final String GIFHEIGHT_FIELD = "gif_height"; + @JsonProperty(GIFHEIGHT_FIELD) + private Integer gifHeight; ///< Optional. Height of the GIF + public static final String THUMBURL_FIELD = "thumb_url"; + @JsonProperty(THUMBURL_FIELD) + private String thumbUrl; ///< Optional. URL of a static thumbnail for the result (jpeg or gif) + public static final String TITLE_FIELD = "title"; + @JsonProperty(TITLE_FIELD) + private String title; ///< Optional. Title for the result + public static final String CAPTION_FIELD = "caption"; + @JsonProperty(CAPTION_FIELD) + private String caption; ///< Optional. Caption of the GIF file to be sent + public static final String MESSAGETEXT_FIELD = "message_text"; + @JsonProperty(MESSAGETEXT_FIELD) + private String messageText; ///< Optional. Text of a message to be sent instead of the animation + public static final String PARSEMODE_FIELD = "parse_mode"; + @JsonProperty(PARSEMODE_FIELD) + private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. + public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; + @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) + private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message + + public String getType() { + return type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getMessageText() { + return messageText; + } + + public void setMessageText(String messageText) { + this.messageText = messageText; + } + + public String getParseMode() { + return parseMode; + } + + public void setParseMode(String parseMode) { + this.parseMode = parseMode; + } + + public Boolean getDisableWebPagePreview() { + return disableWebPagePreview; + } + + public void setDisableWebPagePreview(Boolean disableWebPagePreview) { + this.disableWebPagePreview = disableWebPagePreview; + } + + public String getGifUrl() { + return gifUrl; + } + + public void setGifUrl(String gifUrl) { + this.gifUrl = gifUrl; + } + + public Integer getGifWidth() { + return gifWidth; + } + + public void setGifWidth(Integer gifWidth) { + this.gifWidth = gifWidth; + } + + public Integer getGifHeight() { + return gifHeight; + } + + public void setGifHeight(Integer gifHeight) { + this.gifHeight = gifHeight; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public String getCaption() { + return caption; + } + + public void setCaption(String caption) { + this.caption = caption; + } + + @Override + public JSONObject toJson() { + JSONObject jsonObject = new JSONObject(); + + jsonObject.put(TYPE_FIELD, this.type); + jsonObject.put(ID_FIELD, this.id); + jsonObject.put(GIFURL_FIELD, this.gifUrl); + if (parseMode != null) { + jsonObject.put(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (gifWidth != null) { + jsonObject.put(GIFWIDTH_FIELD, this.gifWidth); + } + if (gifHeight != null) { + jsonObject.put(GIFHEIGHT_FIELD, this.gifHeight); + } + if (thumbUrl != null) { + jsonObject.put(THUMBURL_FIELD, this.thumbUrl); + } + if (title != null) { + jsonObject.put(TITLE_FIELD, this.title); + } + if (caption != null) { + jsonObject.put(CAPTION_FIELD, this.caption); + } + if (messageText != null) { + jsonObject.put(MESSAGETEXT_FIELD, this.messageText); + } + + return jsonObject; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(TYPE_FIELD, type); + gen.writeStringField(ID_FIELD, id); + gen.writeStringField(GIFURL_FIELD, this.gifUrl); + + if (parseMode != null) { + gen.writeStringField(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (gifWidth != null) { + gen.writeNumberField(GIFWIDTH_FIELD, this.gifWidth); + } + if (gifHeight != null) { + gen.writeNumberField(GIFHEIGHT_FIELD, this.gifHeight); + } + if (thumbUrl != null) { + gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); + } + if (title != null) { + gen.writeStringField(TITLE_FIELD, this.title); + } + if (caption != null) { + gen.writeStringField(CAPTION_FIELD, this.caption); + } + if (messageText != null) { + gen.writeStringField(MESSAGETEXT_FIELD, this.messageText); + } + + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/objects/InlineQueryResultMpeg4Gif.java b/src/main/java/org/telegram/api/objects/InlineQueryResultMpeg4Gif.java new file mode 100644 index 0000000..955650c --- /dev/null +++ b/src/main/java/org/telegram/api/objects/InlineQueryResultMpeg4Gif.java @@ -0,0 +1,214 @@ +package org.telegram.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). + * By default, this animated MPEG-4 file will be sent by the user with optional caption. + * Alternatively, you can provide message_text to send it instead of the animation. + * @date 01 of January of 2016 + */ +public class InlineQueryResultMpeg4Gif implements InlineQueryResult { + + public static final String TYPE_FIELD = "type"; + @JsonProperty(TYPE_FIELD) + private final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif" + public static final String ID_FIELD = "id"; + @JsonProperty(ID_FIELD) + private String id; ///< Unique identifier of this result + public static final String MPEG4URL_FIELD = "mpeg4_url"; + @JsonProperty(MPEG4URL_FIELD) + private String mpeg4Url; ///< A valid URL for the MP4 file. File size must not exceed 1MB + public static final String MPEG4WIDTH_FIELD = "mpeg4_width"; + @JsonProperty(MPEG4WIDTH_FIELD) + private Integer mpeg4Width; ///< Optional. Video width + public static final String MPEG4HEIGHT_FIELD = "mpeg4_height"; + @JsonProperty(MPEG4HEIGHT_FIELD) + private Integer mpeg4Height; ///< Optional. Video height + public static final String THUMBURL_FIELD = "thumb_url"; + @JsonProperty(THUMBURL_FIELD) + private String thumbUrl; ///< Optional. URL of the static thumbnail (jpeg or gif) for the result + public static final String TITLE_FIELD = "title"; + @JsonProperty(TITLE_FIELD) + private String title; ///< Optional. Title for the result + public static final String CAPTION_FIELD = "caption"; + @JsonProperty(CAPTION_FIELD) + private String caption; ///< Optional. Caption of the MPEG-4 file to be sent + public static final String MESSAGETEXT_FIELD = "message_text"; + @JsonProperty(MESSAGETEXT_FIELD) + private String messageText; ///< Optional. Text of a message to be sent instead of the animation + public static final String PARSEMODE_FIELD = "parse_mode"; + @JsonProperty(PARSEMODE_FIELD) + private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. + public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; + @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) + private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message + + public String getType() { + return type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getMessageText() { + return messageText; + } + + public void setMessageText(String messageText) { + this.messageText = messageText; + } + + public String getParseMode() { + return parseMode; + } + + public void setParseMode(String parseMode) { + this.parseMode = parseMode; + } + + public Boolean getDisableWebPagePreview() { + return disableWebPagePreview; + } + + public void setDisableWebPagePreview(Boolean disableWebPagePreview) { + this.disableWebPagePreview = disableWebPagePreview; + } + + public String getMpeg4Url() { + return mpeg4Url; + } + + public void setMpeg4Url(String mpeg4Url) { + this.mpeg4Url = mpeg4Url; + } + + public Integer getMpeg4Width() { + return mpeg4Width; + } + + public void setMpeg4Width(Integer mpeg4Width) { + this.mpeg4Width = mpeg4Width; + } + + public Integer getMpeg4Height() { + return mpeg4Height; + } + + public void setMpeg4Height(Integer mpeg4Height) { + this.mpeg4Height = mpeg4Height; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public String getCaption() { + return caption; + } + + public void setCaption(String caption) { + this.caption = caption; + } + + @Override + public JSONObject toJson() { + JSONObject jsonObject = new JSONObject(); + + jsonObject.put(TYPE_FIELD, this.type); + jsonObject.put(ID_FIELD, this.id); + jsonObject.put(MPEG4URL_FIELD, this.mpeg4Url); + if (parseMode != null) { + jsonObject.put(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (mpeg4Width != null) { + jsonObject.put(MPEG4WIDTH_FIELD, this.mpeg4Width); + } + if (mpeg4Height != null) { + jsonObject.put(MPEG4HEIGHT_FIELD, this.mpeg4Height); + } + if (thumbUrl != null) { + jsonObject.put(THUMBURL_FIELD, this.thumbUrl); + } + if (title != null) { + jsonObject.put(TITLE_FIELD, this.title); + } + if (caption != null) { + jsonObject.put(CAPTION_FIELD, this.caption); + } + if (messageText != null) { + jsonObject.put(MESSAGETEXT_FIELD, this.messageText); + } + + return jsonObject; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(TYPE_FIELD, type); + gen.writeStringField(ID_FIELD, id); + gen.writeStringField(MPEG4URL_FIELD, this.mpeg4Url); + + if (parseMode != null) { + gen.writeStringField(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (mpeg4Width != null) { + gen.writeNumberField(MPEG4WIDTH_FIELD, this.mpeg4Width); + } + if (mpeg4Height != null) { + gen.writeNumberField(MPEG4HEIGHT_FIELD, this.mpeg4Height); + } + if (thumbUrl != null) { + gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); + } + if (title != null) { + gen.writeStringField(TITLE_FIELD, this.title); + } + if (caption != null) { + gen.writeStringField(CAPTION_FIELD, this.caption); + } + if (messageText != null) { + gen.writeStringField(MESSAGETEXT_FIELD, this.messageText); + } + + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/objects/InlineQueryResultPhoto.java b/src/main/java/org/telegram/api/objects/InlineQueryResultPhoto.java new file mode 100644 index 0000000..d20cd40 --- /dev/null +++ b/src/main/java/org/telegram/api/objects/InlineQueryResultPhoto.java @@ -0,0 +1,249 @@ +package org.telegram.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Represents a link to a photo. By default, this photo will be sent by the user with optional caption. + * Alternatively, you can provide message_text to send it instead of photo. + * @date 01 of January of 2016 + */ +public class InlineQueryResultPhoto implements InlineQueryResult { + + public static final String TYPE_FIELD = "type"; + @JsonProperty(TYPE_FIELD) + private final String type = "photo"; ///< Type of the result, must be “photo” + public static final String ID_FIELD = "id"; + @JsonProperty(ID_FIELD) + private String id; ///< Unique identifier of this result + public static final String PHOTOURL_FIELD = "photo_url"; + @JsonProperty(PHOTOURL_FIELD) + private String photoUrl; ///< A valid URL of the photo. Photo size must not exceed 5MB + public static final String MIMETYPE_FIELD = "mime_type"; + @JsonProperty(MIMETYPE_FIELD) + private String mimeType; ///< Optional. MIME type of the photo, defaults to image/jpeg + public static final String PHOTOWIDTH_FIELD = "photo_width"; + @JsonProperty(PHOTOWIDTH_FIELD) + private Integer photoWidth; ///< Optional. Width of the photo + public static final String PHOTOHEIGHT_FIELD = "photo_height"; + @JsonProperty(PHOTOHEIGHT_FIELD) + private Integer photoHeight; ///< Optional. Height of the photo + public static final String THUMBURL_FIELD = "thumb_url"; + @JsonProperty(THUMBURL_FIELD) + private String thumbUrl; ///< Optional. URL of the thumbnail for the photo + public static final String TITLE_FIELD = "title"; + @JsonProperty(TITLE_FIELD) + private String title; ///< Optional. Title for the result + public static final String DESCRIPTION_FIELD = "description"; + @JsonProperty(DESCRIPTION_FIELD) + private String description; ///< Optional. Short description of the result + public static final String CAPTION_FIELD = "caption"; + @JsonProperty(CAPTION_FIELD) + private String caption; ///< Optional. Caption of the photo to be sent + public static final String MESSAGETEXT_FIELD = "message_text"; + @JsonProperty(MESSAGETEXT_FIELD) + private String messageText; ///< Optional. Text of a message to be sent instead of the photo + public static final String PARSEMODE_FIELD = "parse_mode"; + @JsonProperty(PARSEMODE_FIELD) + private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. + public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; + @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) + private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message + + public String getType() { + return type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getMessageText() { + return messageText; + } + + public void setMessageText(String messageText) { + this.messageText = messageText; + } + + public String getParseMode() { + return parseMode; + } + + public void setParseMode(String parseMode) { + this.parseMode = parseMode; + } + + public Boolean getDisableWebPagePreview() { + return disableWebPagePreview; + } + + public void setDisableWebPagePreview(Boolean disableWebPagePreview) { + this.disableWebPagePreview = disableWebPagePreview; + } + + public String getPhotoUrl() { + return photoUrl; + } + + public void setPhotoUrl(String photoUrl) { + this.photoUrl = photoUrl; + } + + public String getMimeType() { + return mimeType; + } + + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } + + public Integer getPhotoWidth() { + return photoWidth; + } + + public void setPhotoWidth(Integer photoWidth) { + this.photoWidth = photoWidth; + } + + public Integer getPhotoHeight() { + return photoHeight; + } + + public void setPhotoHeight(Integer photoHeight) { + this.photoHeight = photoHeight; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getCaption() { + return caption; + } + + public void setCaption(String caption) { + this.caption = caption; + } + + @Override + public JSONObject toJson() { + JSONObject jsonObject = new JSONObject(); + + jsonObject.put(TYPE_FIELD, this.type); + jsonObject.put(ID_FIELD, this.id); + jsonObject.put(PHOTOURL_FIELD, this.photoUrl); + if (parseMode != null) { + jsonObject.put(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (mimeType != null) { + jsonObject.put(MIMETYPE_FIELD, this.mimeType); + } + if (photoWidth != null) { + jsonObject.put(PHOTOWIDTH_FIELD, this.photoWidth); + } + if (photoHeight != null) { + jsonObject.put(PHOTOHEIGHT_FIELD, this.photoHeight); + } + if (description != null) { + jsonObject.put(DESCRIPTION_FIELD, this.description); + } + if (thumbUrl != null) { + jsonObject.put(THUMBURL_FIELD, this.thumbUrl); + } + if (title != null) { + jsonObject.put(TITLE_FIELD, this.title); + } + if (description != null) { + jsonObject.put(DESCRIPTION_FIELD, this.description); + } + if (caption != null) { + jsonObject.put(CAPTION_FIELD, this.caption); + } + if (messageText != null) { + jsonObject.put(MESSAGETEXT_FIELD, this.messageText); + } + + return jsonObject; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(TYPE_FIELD, type); + gen.writeStringField(ID_FIELD, id); + gen.writeStringField(PHOTOURL_FIELD, this.photoUrl); + if (parseMode != null) { + gen.writeStringField(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (mimeType != null) { + gen.writeStringField(MIMETYPE_FIELD, this.mimeType); + } + if (photoWidth != null) { + gen.writeNumberField(PHOTOWIDTH_FIELD, this.photoWidth); + } + if (photoHeight != null) { + gen.writeNumberField(PHOTOHEIGHT_FIELD, this.photoHeight); + } + if (thumbUrl != null) { + gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); + } + if (description != null) { + gen.writeStringField(DESCRIPTION_FIELD, this.description); + } + if (title != null) { + gen.writeStringField(TITLE_FIELD, this.title); + } + if (caption != null) { + gen.writeStringField(CAPTION_FIELD, this.caption); + } + if (messageText != null) { + gen.writeStringField(MESSAGETEXT_FIELD, this.messageText); + } + + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/objects/InlineQueryResultVideo.java b/src/main/java/org/telegram/api/objects/InlineQueryResultVideo.java new file mode 100644 index 0000000..a946fb8 --- /dev/null +++ b/src/main/java/org/telegram/api/objects/InlineQueryResultVideo.java @@ -0,0 +1,245 @@ +package org.telegram.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import org.json.JSONObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Represents link to a page containing an embedded video player or a video file. + * @date 01 of January of 2016 + */ +public class InlineQueryResultVideo implements InlineQueryResult { + + public static final String TYPE_FIELD = "type"; + @JsonProperty(TYPE_FIELD) + private final String type = "video"; ///< Type of the result, must be "video" + public static final String ID_FIELD = "id"; + @JsonProperty(ID_FIELD) + private String id; ///< Unique identifier of this result + public static final String MIMETYPE_FIELD = "mime_type"; + @JsonProperty(MIMETYPE_FIELD) + private String mimeType; ///< Mime type of the content of video url, i.e. “text/html” or “video/mp4” + public static final String VIDEOURL_FIELD = "video_url"; + @JsonProperty(VIDEOURL_FIELD) + private String videoUrl; ///< A valid URL for the embedded video player or video file + public static final String VIDEOWIDTH_FIELD = "video_width"; + @JsonProperty(VIDEOWIDTH_FIELD) + private Integer videoWidth; ///< Optional. Video width + public static final String VIDEOHEIGHT_FIELD = "video_height"; + @JsonProperty(VIDEOHEIGHT_FIELD) + private Integer videoHeight; ///< Optional. Video height + public static final String VIDEODURATION_FIELD = "video_duration"; + @JsonProperty(VIDEODURATION_FIELD) + private Integer videoDuration; ///< Optional. Video duration in seconds + public static final String THUMBURL_FIELD = "thumb_url"; + @JsonProperty(THUMBURL_FIELD) + private String thumbUrl; ///< Optional. URL of the thumbnail (jpeg only) for the video + public static final String TITLE_FIELD = "title"; + @JsonProperty(TITLE_FIELD) + private String title; ///< Optional. Title for the result + public static final String DESCRIPTION_FIELD = "description"; + @JsonProperty(DESCRIPTION_FIELD) + private String description; ///< Optional. Short description of the result + public static final String MESSAGETEXT_FIELD = "message_text"; + @JsonProperty(MESSAGETEXT_FIELD) + private String messageText; ///< Optional. Text of a message to be sent instead of the video + public static final String PARSEMODE_FIELD = "parse_mode"; + @JsonProperty(PARSEMODE_FIELD) + private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. + public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; + @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) + private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message + + public String getType() { + return type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getMessageText() { + return messageText; + } + + public void setMessageText(String messageText) { + this.messageText = messageText; + } + + public String getParseMode() { + return parseMode; + } + + public void setParseMode(String parseMode) { + this.parseMode = parseMode; + } + + public Boolean getDisableWebPagePreview() { + return disableWebPagePreview; + } + + public void setDisableWebPagePreview(Boolean disableWebPagePreview) { + this.disableWebPagePreview = disableWebPagePreview; + } + + public String getMimeType() { + return mimeType; + } + + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } + + public String getVideoUrl() { + return videoUrl; + } + + public void setVideoUrl(String videoUrl) { + this.videoUrl = videoUrl; + } + + public Integer getVideoWidth() { + return videoWidth; + } + + public void setVideoWidth(Integer videoWidth) { + this.videoWidth = videoWidth; + } + + public Integer getVideoHeight() { + return videoHeight; + } + + public void setVideoHeight(Integer videoHeight) { + this.videoHeight = videoHeight; + } + + public Integer getVideoDuration() { + return videoDuration; + } + + public void setVideoDuration(Integer videoDuration) { + this.videoDuration = videoDuration; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public JSONObject toJson() { + JSONObject jsonObject = new JSONObject(); + + jsonObject.put(TYPE_FIELD, this.type); + jsonObject.put(ID_FIELD, this.id); + jsonObject.put(VIDEOURL_FIELD, this.videoUrl); + if (mimeType != null) { + jsonObject.put(MIMETYPE_FIELD, this.mimeType); + } + if (messageText != null) { + jsonObject.put(MESSAGETEXT_FIELD, this.messageText); + } + if (parseMode != null) { + jsonObject.put(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (videoWidth != null) { + jsonObject.put(VIDEOWIDTH_FIELD, this.videoWidth); + } + if (videoHeight != null) { + jsonObject.put(VIDEOHEIGHT_FIELD, this.videoHeight); + } + if (videoDuration != null) { + jsonObject.put(VIDEODURATION_FIELD, this.videoDuration); + } + if (thumbUrl != null) { + jsonObject.put(THUMBURL_FIELD, this.thumbUrl); + } + if (title != null) { + jsonObject.put(TITLE_FIELD, this.title); + } + if (description != null) { + jsonObject.put(DESCRIPTION_FIELD, this.description); + } + + return jsonObject; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(TYPE_FIELD, type); + gen.writeStringField(ID_FIELD, id); + gen.writeStringField(VIDEOURL_FIELD, this.videoUrl); + if (mimeType != null) { + gen.writeStringField(MIMETYPE_FIELD, this.mimeType); + } + if (messageText != null) { + gen.writeStringField(MESSAGETEXT_FIELD, this.messageText); + } + if (parseMode != null) { + gen.writeStringField(PARSEMODE_FIELD, this.parseMode); + } + if (disableWebPagePreview != null) { + gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); + } + if (videoWidth != null) { + gen.writeNumberField(VIDEOWIDTH_FIELD, this.videoWidth); + } + if (videoHeight != null) { + gen.writeNumberField(VIDEOHEIGHT_FIELD, this.videoHeight); + } + if (videoDuration != null) { + gen.writeNumberField(VIDEODURATION_FIELD, this.videoDuration); + } + if (thumbUrl != null) { + gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); + } + if (title != null) { + gen.writeStringField(TITLE_FIELD, this.title); + } + if (description != null) { + gen.writeStringField(DESCRIPTION_FIELD, this.description); + } + + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/api/objects/Location.java b/src/main/java/org/telegram/api/objects/Location.java index bf1a63b..fae7c65 100644 --- a/src/main/java/org/telegram/api/objects/Location.java +++ b/src/main/java/org/telegram/api/objects/Location.java @@ -61,10 +61,6 @@ public class Location implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/Message.java b/src/main/java/org/telegram/api/objects/Message.java index e6e66b7..7bc1af8 100644 --- a/src/main/java/org/telegram/api/objects/Message.java +++ b/src/main/java/org/telegram/api/objects/Message.java @@ -24,17 +24,13 @@ public class Message implements BotApiObject { private Integer messageId; ///< Integer Unique message identifier public static final String FROM_FIELD = "from"; @JsonProperty(FROM_FIELD) - private User from; ///< Sender + private User from; ///< Optional. Sender, can be empty for messages sent to channels public static final String DATE_FIELD = "date"; @JsonProperty(DATE_FIELD) private Integer date; ///< Date the message was sent in Unix time public static final String CHAT_FIELD = "chat"; - /** - * Conversation the message belongs to in case of a private message (@see User)or - * Conversation the message belongs to in case of a group (@see GroupChat) - */ @JsonProperty(CHAT_FIELD) - private Chat chat; ///< Conversation the message belongs to in case of a private message + private Chat chat; ///< Conversation the message belongs to public static final String FORWARDFROM_FIELD = "forward_from"; @JsonProperty(FORWARDFROM_FIELD) private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message @@ -73,13 +69,13 @@ public class Message implements BotApiObject { private User leftChatParticipant; ///< Optional. A member was removed from the group, information about them (this member may be bot itself) public static final String NEWCHATTITLE_FIELD = "new_chat_title"; @JsonProperty(NEWCHATTITLE_FIELD) - private String newChatTitle; ///< Optional. A group title was changed to this value + private String newChatTitle; ///< Optional. A chat title was changed to this value public static final String NEWCHATPHOTO_FIELD = "new_chat_photo"; @JsonProperty(NEWCHATPHOTO_FIELD) - private List newChatPhoto; ///< Optional. A group photo was change to this value + private List newChatPhoto; ///< Optional. A chat photo was change to this value public static final String DELETECHATPHOTO_FIELD = "delete_chat_photo"; @JsonProperty(DELETECHATPHOTO_FIELD) - private Boolean deleteChatPhoto; ///< Optional. Informs that the group photo was deleted + private Boolean deleteChatPhoto; ///< Optional. Informs that the chat photo was deleted public static final String GROUPCHATCREATED_FIELD = "group_chat_created"; @JsonProperty(GROUPCHATCREATED_FIELD) private Boolean groupchatCreated; ///< Optional. Informs that the group has been created @@ -89,6 +85,18 @@ public class Message implements BotApiObject { public static final String VOICE_FIELD = "voice"; @JsonProperty(VOICE_FIELD) private Voice voice; ///< Optional. Message is a voice message, information about the file + public static final String SUPERGROUPCREATED_FIELD = "supergroup_chat_created"; + @JsonProperty(SUPERGROUPCREATED_FIELD) + private Boolean superGroupCreated; ///< Optional. Informs that the supergroup has been created + public static final String CHANNELCHATCREATED_FIELD = "channel_chat_created"; + @JsonProperty(CHANNELCHATCREATED_FIELD) + private Boolean channelChatCreated; ///< Optional. Informs that the channel has been created + public static final String MIGRATETOCHAT_FIELD = "migrate_to_chat_id"; + @JsonProperty(MIGRATETOCHAT_FIELD) + private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value + public static final String MIGRATEFROMCHAT_FIELD = "migrate_from_chat_id"; + @JsonProperty(MIGRATEFROMCHAT_FIELD) + private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value public Message() { super(); @@ -97,7 +105,9 @@ public class Message implements BotApiObject { public Message(JSONObject jsonObject) { super(); this.messageId = jsonObject.getInt(MESSAGEID_FIELD); - this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); + if (jsonObject.has(FROM_FIELD)) { + this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); + } this.date = jsonObject.getInt(DATE_FIELD); this.chat = new Chat(jsonObject.getJSONObject(CHAT_FIELD)); if (jsonObject.has(FORWARDFROM_FIELD)) { @@ -157,10 +167,22 @@ public class Message implements BotApiObject { } } if (jsonObject.has(DELETECHATPHOTO_FIELD)) { - this.deleteChatPhoto = jsonObject.getBoolean(DELETECHATPHOTO_FIELD); + this.deleteChatPhoto = true; } if (jsonObject.has(GROUPCHATCREATED_FIELD)) { - this.groupchatCreated = jsonObject.getBoolean(GROUPCHATCREATED_FIELD); + this.groupchatCreated = true; + } + if (jsonObject.has(SUPERGROUPCREATED_FIELD)) { + this.superGroupCreated = true; + } + if (jsonObject.has(CHANNELCHATCREATED_FIELD)) { + this.channelChatCreated = true; + } + if (jsonObject.has(MIGRATETOCHAT_FIELD)) { + this.migrateToChatId = jsonObject.getLong(MIGRATETOCHAT_FIELD); + } + if (jsonObject.has(MIGRATEFROMCHAT_FIELD)) { + this.migrateFromChatId = jsonObject.getLong(MIGRATEFROMCHAT_FIELD); } } @@ -192,7 +214,19 @@ public class Message implements BotApiObject { return chat.isGroupChat(); } - public Integer getChatId() { + public boolean isUserMessage() { + return chat.isUserChat(); + } + + public boolean isChannelMessage() { + return chat.isChannelChat(); + } + + public boolean isSuperGroupMessage() { + return chat.isSuperGroupChat(); + } + + public Long getChatId() { return chat.getId(); } @@ -221,7 +255,7 @@ public class Message implements BotApiObject { } public boolean hasText() { - return text != null; + return text != null && !text.isEmpty(); } public String getText() { @@ -368,6 +402,38 @@ public class Message implements BotApiObject { this.voice = voice; } + public Boolean getSuperGroupCreated() { + return superGroupCreated; + } + + public void setSuperGroupCreated(Boolean superGroupCreated) { + this.superGroupCreated = superGroupCreated; + } + + public Boolean getChannelChatCreated() { + return channelChatCreated; + } + + public void setChannelChatCreated(Boolean channelChatCreated) { + this.channelChatCreated = channelChatCreated; + } + + public Long getMigrateToChatId() { + return migrateToChatId; + } + + public void setMigrateToChatId(Long migrateToChatId) { + this.migrateToChatId = migrateToChatId; + } + + public Long getMigrateFromChatId() { + return migrateFromChatId; + } + + public void setMigrateFromChatId(Long migrateFromChatId) { + this.migrateFromChatId = migrateFromChatId; + } + @Override public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); @@ -439,76 +505,24 @@ public class Message implements BotApiObject { if (groupchatCreated != null) { gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated); } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - if (forwardFrom != null) { - gen.writeObjectField(FORWARDFROM_FIELD, forwardFrom); - } - if (forwardDate != null) { - gen.writeNumberField(FORWARDDATE_FIELD, forwardDate); - } - if (text != null) { - gen.writeStringField(TEXT_FIELD, text); - } - if (audio != null) { - gen.writeObjectField(AUDIO_FIELD, audio); - } - if (document != null) { - gen.writeObjectField(DOCUMENT_FIELD, document); - } - if (photo != null && photo.size() > 0) { - gen.writeArrayFieldStart(PHOTO_FIELD); - for (PhotoSize photoSize : photo) { - gen.writeObject(photoSize); - } - gen.writeEndArray(); - } - if (sticker != null) { - gen.writeObjectField(STICKER_FIELD, sticker); - } - if (video != null) { - gen.writeObjectField(VIDEO_FIELD, video); - } - if (contact != null) { - gen.writeObjectField(CONTACT_FIELD, contact); + if (superGroupCreated != null) { + gen.writeBooleanField(SUPERGROUPCREATED_FIELD, superGroupCreated); } - if (location != null) { - gen.writeObjectField(LOCATION_FIELD, location); + if (channelChatCreated != null) { + gen.writeBooleanField(CHANNELCHATCREATED_FIELD, channelChatCreated); } - if (voice != null) { - gen.writeObjectField(VOICE_FIELD, voice); + if (migrateToChatId != null) { + gen.writeNumberField(MIGRATETOCHAT_FIELD, migrateToChatId); } - if (newChatParticipant != null) { - gen.writeObjectField(NEWCHATPARTICIPANT_FIELD, newChatParticipant); - } - if (leftChatParticipant != null) { - gen.writeObjectField(LEFTCHATPARTICIPANT_FIELD, leftChatParticipant); - } - if (replyToMessage != null) { - gen.writeObjectField(REPLYTOMESSAGE_FIELD, replyToMessage); - } - if (newChatTitle != null) { - gen.writeStringField(NEWCHATTITLE_FIELD, newChatTitle); - } - if (newChatPhoto != null && newChatPhoto.size() > 0) { - gen.writeArrayFieldStart(NEWCHATPHOTO_FIELD); - for (PhotoSize photoSize: newChatPhoto) { - gen.writeObject(photoSize); - } - gen.writeEndArray(); - } - if (deleteChatPhoto != null) { - gen.writeBooleanField(DELETECHATPHOTO_FIELD, deleteChatPhoto); - } - if (groupchatCreated != null) { - gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated); + if (migrateFromChatId != null) { + gen.writeNumberField(MIGRATEFROMCHAT_FIELD, migrateFromChatId); } gen.writeEndObject(); gen.flush(); + } + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/PhotoSize.java b/src/main/java/org/telegram/api/objects/PhotoSize.java index 888616e..5ade74d 100644 --- a/src/main/java/org/telegram/api/objects/PhotoSize.java +++ b/src/main/java/org/telegram/api/objects/PhotoSize.java @@ -91,14 +91,6 @@ public class PhotoSize implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(WIDTH_FIELD, width); - gen.writeNumberField(HEIGHT_FIELD, height); - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/ReplyKeyboardHide.java b/src/main/java/org/telegram/api/objects/ReplyKeyboardHide.java index 0f40d43..c6527a6 100644 --- a/src/main/java/org/telegram/api/objects/ReplyKeyboardHide.java +++ b/src/main/java/org/telegram/api/objects/ReplyKeyboardHide.java @@ -83,10 +83,6 @@ public class ReplyKeyboardHide implements ReplyKeyboard { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeBooleanField(HIDEKEYBOARD_FIELD, hideKeyboard); - gen.writeBooleanField(SELECTIVE_FIELD, selective); - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/ReplyKeyboardMarkup.java b/src/main/java/org/telegram/api/objects/ReplyKeyboardMarkup.java index eaaa2ed..c320af3 100644 --- a/src/main/java/org/telegram/api/objects/ReplyKeyboardMarkup.java +++ b/src/main/java/org/telegram/api/objects/ReplyKeyboardMarkup.java @@ -151,26 +151,6 @@ public class ReplyKeyboardMarkup implements ReplyKeyboard { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeArrayFieldStart(KEYBOARD_FIELD); - for (List innerRow : keyboard) { - gen.writeStartArray(); - for (String element: innerRow) { - gen.writeString(element); - } - gen.writeEndArray(); - } - gen.writeEndArray(); - if (this.oneTimeKeyboad != null) { - gen.writeBooleanField(ONETIMEKEYBOARD_FIELD, oneTimeKeyboad); - } - if (this.resizeKeyboard != null) { - gen.writeBooleanField(RESIZEKEYBOARD_FIELD, resizeKeyboard); - } - if (this.selective != null) { - gen.writeBooleanField(SELECTIVE_FIELD, selective); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/Sticker.java b/src/main/java/org/telegram/api/objects/Sticker.java index 01860ef..d9c700f 100644 --- a/src/main/java/org/telegram/api/objects/Sticker.java +++ b/src/main/java/org/telegram/api/objects/Sticker.java @@ -68,17 +68,6 @@ public class Sticker implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(WIDTH_FIELD, width); - gen.writeNumberField(HEIGHT_FIELD, height); - if (thumb != null) { - gen.writeObjectField(THUMB_FIELD, thumb); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/Update.java b/src/main/java/org/telegram/api/objects/Update.java index 69d297d..26c7d09 100644 --- a/src/main/java/org/telegram/api/objects/Update.java +++ b/src/main/java/org/telegram/api/objects/Update.java @@ -12,23 +12,27 @@ import java.io.IOException; /** * @author Ruben Bermudez * @version 1.0 - * @brief TODO + * @brief This object represents an incoming update. + * Only one of the optional parameters can be present in any given update. * @date 20 of June of 2015 */ public class Update implements BotApiObject { public static final String UPDATEID_FIELD = "update_id"; - /** - * The update‘s unique identifier. - * Update identifiers start from a certain positive number and increase sequentially. - * This ID becomes especially handy if you’re using Webhooks, - * since it allows you to ignore repeated updates or to restore the - * correct update sequence, should they get out of order. - */ @JsonProperty(UPDATEID_FIELD) private Integer updateId; public static final String MESSAGE_FIELD = "message"; @JsonProperty(MESSAGE_FIELD) private Message message; ///< Optional. New incoming message of any kind — text, photo, sticker, etc. + public static final String INLINEQUERY_FIELD = "inline_query"; + @JsonProperty(INLINEQUERY_FIELD) + private InlineQuery inlineQuery; ///< Optional. New incoming inline query + public static final String CHOSENINLINEQUERY_FIELD = "chosen_inline_result"; + @JsonProperty(CHOSENINLINEQUERY_FIELD) + private ChosenInlineQuery chosenInlineQuery; ///< Optional. The result of a inline query that was chosen by a user and sent to their chat partner + + /* + ChosenInlineResult + */ public Update() { super(); @@ -40,6 +44,12 @@ public class Update implements BotApiObject { if (jsonObject.has(MESSAGE_FIELD)) { this.message = new Message(jsonObject.getJSONObject(MESSAGE_FIELD)); } + if (jsonObject.has(INLINEQUERY_FIELD)) { + this.inlineQuery = new InlineQuery(jsonObject.getJSONObject(INLINEQUERY_FIELD)); + } + if (jsonObject.has(CHOSENINLINEQUERY_FIELD)) { + this.chosenInlineQuery = new ChosenInlineQuery(jsonObject.getJSONObject(CHOSENINLINEQUERY_FIELD)); + } } public Integer getUpdateId() { @@ -50,6 +60,26 @@ public class Update implements BotApiObject { return message; } + public InlineQuery getInlineQuery() { + return inlineQuery; + } + + public ChosenInlineQuery getChosenInlineQuery() { + return chosenInlineQuery; + } + + public boolean hasMessage() { + return message != null; + } + + public boolean hasInlineQuery() { + return inlineQuery != null; + } + + public boolean hasChosenInlineQuery() { + return chosenInlineQuery != null; + } + @Override public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); @@ -57,18 +87,18 @@ public class Update implements BotApiObject { if (message != null) { gen.writeObjectField(MESSAGE_FIELD, message); } + if (inlineQuery != null) { + gen.writeObjectField(INLINEQUERY_FIELD, inlineQuery); + } + if (chosenInlineQuery != null) { + gen.writeObjectField(CHOSENINLINEQUERY_FIELD, chosenInlineQuery); + } gen.writeEndObject(); gen.flush(); } @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(UPDATEID_FIELD, updateId); - if (message != null) { - gen.writeObjectField(MESSAGE_FIELD, message); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/User.java b/src/main/java/org/telegram/api/objects/User.java index a767af6..5ccaf22 100644 --- a/src/main/java/org/telegram/api/objects/User.java +++ b/src/main/java/org/telegram/api/objects/User.java @@ -79,16 +79,6 @@ public class User implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(ID_FIELD, id); - gen.writeStringField(FIRSTNAME_FIELD, firstName); - if (lastName != null) { - gen.writeStringField(LASTNAME_FIELD, lastName); - } - if (userName != null) { - gen.writeStringField(USERNAME_FIELD, userName); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/UserProfilePhotos.java b/src/main/java/org/telegram/api/objects/UserProfilePhotos.java index 962e631..23ace48 100644 --- a/src/main/java/org/telegram/api/objects/UserProfilePhotos.java +++ b/src/main/java/org/telegram/api/objects/UserProfilePhotos.java @@ -85,20 +85,6 @@ public class UserProfilePhotos implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(TOTALCOUNT_FIELD, totalCount); - if (totalCount > 0) { - gen.writeArrayFieldStart(PHOTOS_FIELD); - for (List photoSizeList : photos) { - gen.writeStartArray(); - for (PhotoSize photoSize: photoSizeList) { - gen.writeObject(photoSize); - } - gen.writeEndArray(); - } - gen.writeEndArray(); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/Video.java b/src/main/java/org/telegram/api/objects/Video.java index dbd0f06..b5be814 100644 --- a/src/main/java/org/telegram/api/objects/Video.java +++ b/src/main/java/org/telegram/api/objects/Video.java @@ -137,21 +137,6 @@ public class Video implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(WIDTH_FIELD, width); - gen.writeNumberField(HEIGHT_FIELD, height); - gen.writeNumberField(DURATION_FIELD, duration); - if (thumb != null) { - gen.writeObjectField(THUMB_FIELD, thumb); - } - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/api/objects/Voice.java b/src/main/java/org/telegram/api/objects/Voice.java index ea01d3d..06fc9fb 100644 --- a/src/main/java/org/telegram/api/objects/Voice.java +++ b/src/main/java/org/telegram/api/objects/Voice.java @@ -94,16 +94,6 @@ public class Voice implements BotApiObject { @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(DURATION_FIELD, duration); - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); + serialize(gen, serializers); } } diff --git a/src/main/java/org/telegram/database/ConectionDB.java b/src/main/java/org/telegram/database/ConectionDB.java index fa75142..5a98513 100644 --- a/src/main/java/org/telegram/database/ConectionDB.java +++ b/src/main/java/org/telegram/database/ConectionDB.java @@ -19,7 +19,7 @@ import java.sql.*; * @date 3/12/14 */ public class ConectionDB { - private static volatile BotLogger log = BotLogger.getLogger(ConectionDB.class.getName()); + private static final String LOGTAG = "CONNECTIONDB"; private Connection currentConection; public ConectionDB() { @@ -32,7 +32,7 @@ public class ConectionDB { Class.forName(BuildVars.controllerDB).newInstance(); connection = DriverManager.getConnection(BuildVars.linkDB, BuildVars.userDB, BuildVars.password); } catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return connection; @@ -42,7 +42,7 @@ public class ConectionDB { try { this.currentConection.close(); } catch (SQLException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } @@ -81,7 +81,7 @@ public class ConectionDB { } } } catch (SQLException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return max; } diff --git a/src/main/java/org/telegram/database/CreationStrings.java b/src/main/java/org/telegram/database/CreationStrings.java index 59a2fb5..8b56782 100644 --- a/src/main/java/org/telegram/database/CreationStrings.java +++ b/src/main/java/org/telegram/database/CreationStrings.java @@ -7,7 +7,7 @@ package org.telegram.database; * @date 15 of May of 2015 */ public class CreationStrings { - public static final int version = 6; + public static final int version = 7; public static final String createVersionTable = "CREATE TABLE IF NOT EXISTS Versions(ID INTEGER PRIMARY KEY AUTO_INCREMENT, Version INTEGER);"; public static final String insertCurrentVersion = "INSERT IGNORE INTO Versions (Version) VALUES(%d);"; public static final String createFilesTable = "CREATE TABLE IF NOT EXISTS Files (fileId VARCHAR(100) PRIMARY KEY, userId INTEGER NOT NULL, caption TEXT NOT NULL)"; @@ -21,7 +21,7 @@ public class CreationStrings { public static final String createUserLanguageDatabase = "CREATE TABLE IF NOT EXISTS UserLanguage (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL)"; public static final String createUserWeatherOptionDatabase = "CREATE TABLE IF NOT EXISTS UserWeatherOptions (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " + "units VARCHAR(10) NOT NULL DEFAULT 'metric')"; - public static final String createWeatherStateTable = "CREATE TABLE IF NOT EXISTS WeatherState (userId INTEGER NOT NULL, chatId INTEGER NOT NULL, state INTEGER NOT NULL DEFAULT 0, " + + public static final String createWeatherStateTable = "CREATE TABLE IF NOT EXISTS WeatherState (userId INTEGER NOT NULL, chatId BIGINT NOT NULL, state INTEGER NOT NULL DEFAULT 0, " + "languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " + "CONSTRAINT `watherPrimaryKey` PRIMARY KEY(userId,chatId));"; public static final String createWeatherAlertTable = "CREATE TABLE IF NOT EXISTS WeatherAlert (id INTEGER PRIMARY KEY AUTO_INCREMENT, userId INTEGER NOT NULL, cityId INTEGER NOT NULL, " + diff --git a/src/main/java/org/telegram/database/DatabaseManager.java b/src/main/java/org/telegram/database/DatabaseManager.java index fd5b168..861ed4c 100644 --- a/src/main/java/org/telegram/database/DatabaseManager.java +++ b/src/main/java/org/telegram/database/DatabaseManager.java @@ -9,7 +9,6 @@ package org.telegram.database; import org.telegram.services.BotLogger; import org.telegram.structure.WeatherAlert; -import org.telegram.updateshandlers.WeatherHandlers; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -26,7 +25,8 @@ import java.util.List; * @date 3/12/14 */ public class DatabaseManager { - private static volatile BotLogger log = BotLogger.getLogger(DatabaseManager.class.getName()); ///< Logger + private static final String LOGTAG = "DATABASEMANAGER"; + private static volatile DatabaseManager instance; private static volatile ConectionDB connetion; @@ -36,7 +36,7 @@ public class DatabaseManager { private DatabaseManager() { connetion = new ConectionDB(); final int currentVersion = connetion.checkVersion(); - log.info("Current db version: " + currentVersion); + BotLogger.info(LOGTAG, "Current db version: " + currentVersion); if (currentVersion < CreationStrings.version) { recreateTable(currentVersion); } @@ -86,9 +86,12 @@ public class DatabaseManager { if (currentVersion == 5) { currentVersion = updateToVersion6(); } + if (currentVersion == 6) { + currentVersion = updateToVersion7(); + } connetion.commitTransaction(); } catch (SQLException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } @@ -124,6 +127,12 @@ public class DatabaseManager { return 6; } + private int updateToVersion7() throws SQLException { + connetion.executeQuery("ALTER TABLE WeatherState MODIFY chatId BIGINT NOT NULL"); + connetion.executeQuery(String.format(CreationStrings.insertCurrentVersion, 7)); + return 7; + } + private int createNewTables() throws SQLException { connetion.executeQuery(CreationStrings.createVersionTable); connetion.executeQuery(CreationStrings.createFilesTable); @@ -411,12 +420,12 @@ public class DatabaseManager { return updatedRows > 0; } - public int getWeatherState(Integer userId, Integer chatId) { + public int getWeatherState(Integer userId, Long chatId) { int state = 0; try { final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT state FROM WeatherState WHERE userId = ? AND chatId = ?"); preparedStatement.setInt(1, userId); - preparedStatement.setInt(2, chatId); + preparedStatement.setLong(2, chatId); final ResultSet result = preparedStatement.executeQuery(); if (result.next()) { state = result.getInt("state"); @@ -427,12 +436,12 @@ public class DatabaseManager { return state; } - public boolean insertWeatherState(Integer userId, Integer chatId, int state) { + public boolean insertWeatherState(Integer userId, Long chatId, int state) { int updatedRows = 0; try { final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO WeatherState (userId, chatId, state) VALUES (?, ?, ?)"); preparedStatement.setInt(1, userId); - preparedStatement.setInt(2, chatId); + preparedStatement.setLong(2, chatId); preparedStatement.setInt(3, state); updatedRows = preparedStatement.executeUpdate(); } catch (SQLException e) { diff --git a/src/main/java/org/telegram/services/BotLogger.java b/src/main/java/org/telegram/services/BotLogger.java index 9568050..fd180b9 100644 --- a/src/main/java/org/telegram/services/BotLogger.java +++ b/src/main/java/org/telegram/services/BotLogger.java @@ -4,9 +4,7 @@ import org.telegram.BuildVars; import javax.validation.constraints.NotNull; import java.io.*; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.concurrent.ConcurrentHashMap; +import java.time.LocalDateTime; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.ConsoleHandler; import java.util.logging.Level; @@ -14,57 +12,38 @@ import java.util.logging.Logger; /** * @author Ruben Bermudez - * @version 1.0 - * @brief Logger + * @version 2.0 + * @brief Logger to file * @date 21/01/15 */ public class BotLogger { - private volatile Object lockToWrite = new Object(); - - private final Logger logger; + private static final Object lockToWrite = new Object(); private static volatile PrintWriter logginFile; - private Calendar lastFileDate; private static volatile String currentFileName; + private static final Logger logger = Logger.getLogger("Tsupport Bot"); + private static volatile LocalDateTime lastFileDate; private static LoggerThread loggerThread = new LoggerThread(); - private static volatile ConcurrentHashMap instances = new ConcurrentHashMap<>(); - private final static ConcurrentLinkedQueue logsToFile = new ConcurrentLinkedQueue<>(); + private static final ConcurrentLinkedQueue logsToFile = new ConcurrentLinkedQueue<>(); static { - - loggerThread.start(); - } - - public static BotLogger getLogger(@NotNull String className) { - if (!instances.containsKey(className)) { - synchronized (BotLogger.class) { - if (!instances.containsKey(className)) { - BotLogger instance = new BotLogger(className); - instances.put(className, instance); - return instance; - } else { - return instances.get(className); - } - } - } else { - return instances.get(className); - } - } - - private BotLogger(String classname) { - logger = Logger.getLogger(classname); logger.setLevel(Level.ALL); - ConsoleHandler handler = new ConsoleHandler(); - handler.setLevel(Level.ALL); - logger.addHandler(handler); - lastFileDate = new GregorianCalendar(); - if (currentFileName == null || currentFileName.length() == 0) { - currentFileName = BuildVars.pathToLogs + dateFormaterForFileName(lastFileDate) + ".log"; + logger.addHandler(new ConsoleHandler()); + loggerThread.start(); + lastFileDate = LocalDateTime.now(); + if ((currentFileName == null) || (currentFileName.compareTo("") == 0)) { + currentFileName = dateFormatterForFileName(lastFileDate) + ".log"; try { - File file = new File(currentFileName); - if (!file.exists()) { - file.createNewFile(); + final File file = new File(currentFileName); + if (file.exists()) { + logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); + } else { + final boolean created = file.createNewFile(); + if (created) { + logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); + } else { + throw new NullPointerException("File for logging error"); + } } - logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); } catch (IOException e) { e.printStackTrace(); } @@ -72,271 +51,261 @@ public class BotLogger { } } - - public void log(@NotNull Level level, String msg) { - logger.log(level, msg); - logToFile(level, msg); + public static void log(@NotNull Level level, String tag, String msg) { + logger.log(level, String.format("[%s] %s", tag, msg)); + logToFile(level, tag, msg); } - public void severe(String msg) { - logger.severe(msg); - logToFile(Level.SEVERE, msg); + public static void severe(String tag, String msg) { + logger.severe(String.format("[%s] %s", tag, msg)); + logToFile(Level.SEVERE, tag, msg); } - public void warn(String msg) { - warning(msg); + public static void warn(String tag, String msg) { + warning(tag, msg); } - public void debug(String msg) { - fine(msg); + public static void debug(String tag, String msg) { + fine(tag, msg); } - public void error(String msg) { - severe(msg); + public static void error(String tag, String msg) { + severe(tag, msg); } - public void trace(String msg) { - finer(msg); + public static void trace(String tag, String msg) { + finer(tag, msg); } - public void warning(String msg) { - logger.warning(msg); - logToFile(Level.WARNING, msg); + public static void warning(String tag, String msg) { + logger.warning(String.format("[%s] %s", tag, msg)); + logToFile(Level.WARNING, tag, msg); } - public void info(String msg) { - logger.info(msg); - logToFile(Level.INFO, msg); + public static void info(String tag, String msg) { + logger.info(String.format("[%s] %s", tag, msg)); + logToFile(Level.INFO, tag, msg); } - public void config(String msg) { - logger.config(msg); - logToFile(Level.CONFIG, msg); + public static void config(String tag, String msg) { + logger.config(String.format("[%s] %s", tag, msg)); + logToFile(Level.CONFIG, tag, msg); } - public void fine(String msg) { - logger.fine(msg); - logToFile(Level.FINE, msg); + public static void fine(String tag, String msg) { + logger.fine(String.format("[%s] %s", tag, msg)); + logToFile(Level.FINE, tag, msg); } - public void finer(String msg) { - logger.finer(msg); - logToFile(Level.FINER, msg); + public static void finer(String tag, String msg) { + logger.finer(String.format("[%s] %s", tag, msg)); + logToFile(Level.FINER, tag, msg); } - public void finest(String msg) { - logger.finest(msg); - logToFile(Level.FINEST, msg); + public static void finest(String tag, String msg) { + logger.finest(String.format("[%s] %s", tag, msg)); + logToFile(Level.FINEST, tag, msg); } - public void log(@NotNull Level level, @NotNull Throwable throwable) { - throwable.printStackTrace(); - logToFile(level, throwable); + public static void log(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable) { + logger.log(level, String.format("[%s] Exception", tag), throwable); + logToFile(level, tag, throwable); } - public void log(@NotNull Level level, String msg, Throwable thrown) { + public static void log(@NotNull Level level, @NotNull String tag, @NotNull String msg, @NotNull Throwable thrown) { logger.log(level, msg, thrown); - logToFile(level, msg ,thrown); + logToFile(level, msg, thrown); } - public void severe(@NotNull Throwable throwable) { - logToFile(Level.SEVERE, throwable); + public static void severe(@NotNull String tag, @NotNull Throwable throwable) { + logToFile(Level.SEVERE, tag, throwable); } - public void warning(@NotNull Throwable throwable) { - logToFile(Level.WARNING, throwable); + public static void warning(@NotNull String tag, @NotNull Throwable throwable) { + logToFile(Level.WARNING, tag, throwable); } - public void info(@NotNull Throwable throwable) { - logToFile(Level.INFO, throwable); + public static void info(@NotNull String tag, @NotNull Throwable throwable) { + logToFile(Level.INFO, tag, throwable); } - public void config(@NotNull Throwable throwable) { - logToFile(Level.CONFIG, throwable); + public static void config(@NotNull String tag, @NotNull Throwable throwable) { + logToFile(Level.CONFIG, tag, throwable); } - public void fine(@NotNull Throwable throwable) { - logToFile(Level.FINE, throwable); + public static void fine(@NotNull String tag, @NotNull Throwable throwable) { + logToFile(Level.FINE, tag, throwable); } - public void finer(@NotNull Throwable throwable) { - logToFile(Level.FINER, throwable); + public static void finer(@NotNull String tag, @NotNull Throwable throwable) { + logToFile(Level.FINER, tag, throwable); } - public void finest(@NotNull Throwable throwable) { - logToFile(Level.FINEST, throwable); + public static void finest(@NotNull String tag, @NotNull Throwable throwable) { + logToFile(Level.FINEST, tag, throwable); } - public void warn(Throwable throwable) { - warning(throwable); + public static void warn(@NotNull String tag, Throwable throwable) { + warning(tag, throwable); } - public void debug(Throwable throwable) { - fine(throwable); + public static void debug(@NotNull String tag, Throwable throwable) { + fine(tag, throwable); } - public void error(Throwable throwable) { - severe(throwable); + public static void error(@NotNull String tag, Throwable throwable) { + severe(tag, throwable); } - public void trace(Throwable throwable) { - finer(throwable); + public static void trace(@NotNull String tag, Throwable throwable) { + finer(tag, throwable); } - public void severe(String msg, @NotNull Throwable throwable) { - log(Level.SEVERE, msg, throwable); + public static void severe(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.SEVERE, tag, msg, throwable); } - public void warning(String msg, @NotNull Throwable throwable) { - log(Level.WARNING, msg, throwable); + public static void warning(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.WARNING, tag, msg, throwable); } - public void info(String msg, @NotNull Throwable throwable) { - log(Level.INFO, msg, throwable); + public static void info(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.INFO, tag, msg, throwable); } - public void config(String msg, @NotNull Throwable throwable) { - log(Level.CONFIG, msg, throwable); + public static void config(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.CONFIG, tag, msg, throwable); } - public void fine(String msg, @NotNull Throwable throwable) { - log(Level.FINE, msg, throwable); + public static void fine(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.FINE, tag, msg, throwable); } - public void finer(String msg, @NotNull Throwable throwable) { - log(Level.FINER, msg, throwable); + public static void finer(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.FINER, tag, msg, throwable); } - public void finest(String msg, @NotNull Throwable throwable) { + public static void finest(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { log(Level.FINEST, msg, throwable); } - public void warn(String msg, @NotNull Throwable throwable) { - log(Level.WARNING, msg, throwable); + public static void warn(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.WARNING, tag, msg, throwable); } - public void debug(String msg, @NotNull Throwable throwable) { - log(Level.FINE, msg, throwable); + public static void debug(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.FINE, tag, msg, throwable); } - public void error(String msg, @NotNull Throwable throwable) { - log(Level.SEVERE, msg, throwable); + public static void error(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.SEVERE, tag, msg, throwable); } - public void trace(String msg, @NotNull Throwable throwable) { - log(Level.FINER, msg, throwable); + public static void trace(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) { + log(Level.FINER, tag, msg, throwable); } - private boolean isCurrentDate(Calendar calendar) { - if (calendar.get(Calendar.DAY_OF_MONTH) != lastFileDate.get(Calendar.DAY_OF_MONTH)) { - return false; - } - if (calendar.get(Calendar.MONTH) != lastFileDate.get(Calendar.MONTH)) { - return false; - } - if (calendar.get(Calendar.YEAR) != lastFileDate.get(Calendar.YEAR)) { - return false; - } - return true; + private static boolean isCurrentDate(LocalDateTime dateTime) { + return dateTime.toLocalDate().isEqual(lastFileDate.toLocalDate()); } - private String dateFormaterForFileName(@NotNull Calendar calendar) { + private static String dateFormatterForFileName(@NotNull LocalDateTime dateTime) { String dateString = ""; - dateString += calendar.get(Calendar.DAY_OF_MONTH); - dateString += calendar.get(Calendar.MONTH) + 1; - dateString += calendar.get(Calendar.YEAR); + dateString += dateTime.getDayOfMonth(); + dateString += dateTime.getMonthValue(); + dateString += dateTime.getYear(); return dateString; } - private String dateFormaterForLogs(@NotNull Calendar calendar) { + private static String dateFormatterForLogs(@NotNull LocalDateTime dateTime) { String dateString = "["; - dateString += calendar.get(Calendar.DAY_OF_MONTH) + "_"; - dateString += (calendar.get(Calendar.MONTH) + 1) + "_"; - dateString += calendar.get(Calendar.YEAR) + "_"; - dateString += calendar.get(Calendar.HOUR_OF_DAY) + "_"; - dateString += calendar.get(Calendar.MINUTE) + ":"; - dateString += calendar.get(Calendar.SECOND); + dateString += dateTime.getDayOfMonth() + "_"; + dateString += dateTime.getMonthValue() + "_"; + dateString += dateTime.getYear() + "_"; + dateString += dateTime.getHour() + ":"; + dateString += dateTime.getMinute() + ":"; + dateString += dateTime.getSecond(); dateString += "] "; return dateString; } - private void updateAndCreateFile(Calendar calendar) { - if (isCurrentDate(calendar)) { - return; - } - lastFileDate = new GregorianCalendar(); - currentFileName = BuildVars.pathToLogs + dateFormaterForFileName(lastFileDate) + ".log"; - try { - logginFile.flush(); - logginFile.close(); - File file = new File(currentFileName); - if (!file.exists()) { - file.createNewFile(); + private static void updateAndCreateFile(LocalDateTime dateTime) { + if (!isCurrentDate(dateTime)) { + lastFileDate = LocalDateTime.now(); + currentFileName = BuildVars.pathToLogs + dateFormatterForFileName(lastFileDate) + ".log"; + try { + logginFile.flush(); + logginFile.close(); + final File file = new File(currentFileName); + if (file.exists()) { + logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); + } else { + final boolean created = file.createNewFile(); + if (created) { + logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); + } else { + throw new NullPointerException("Error updating log file"); + } + } + } catch (IOException ignored) { } - logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); } } - private void logToFile(@NotNull Level level, Throwable throwable) { - if (!isLoggable(level)){ - return; - } - synchronized (lockToWrite) { - Calendar currentDate = new GregorianCalendar(); - String dateForLog = dateFormaterForLogs(currentDate); - updateAndCreateFile(currentDate); - logThrowableToFile(level, throwable, dateForLog); + + private static void logToFile(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable) { + if (isLoggable(level)) { + synchronized (lockToWrite) { + final LocalDateTime currentDate = LocalDateTime.now(); + final String dateForLog = dateFormatterForLogs(currentDate); + updateAndCreateFile(currentDate); + logThrowableToFile(level, tag, throwable, dateForLog); + } } } - private void logToFile(@NotNull Level level, String msg) { - if (!isLoggable(level)){ - return; - } - synchronized (lockToWrite) { - Calendar currentDate = new GregorianCalendar(); - updateAndCreateFile(currentDate); - String dateForLog = dateFormaterForLogs(currentDate); - logMsgToFile(level, msg, dateForLog); + private static void logToFile(@NotNull Level level, @NotNull String tag, @NotNull String msg) { + if (isLoggable(level)) { + synchronized (lockToWrite) { + final LocalDateTime currentDate = LocalDateTime.now(); + updateAndCreateFile(currentDate); + final String dateForLog = dateFormatterForLogs(currentDate); + logMsgToFile(level, tag, msg, dateForLog); + } } } - private void logToFile(Level level, String msg, Throwable throwable) { - if (!isLoggable(level)){ - return; - } - synchronized (lockToWrite) { - Calendar currentDate = new GregorianCalendar(); - updateAndCreateFile(currentDate); - String dateForLog = dateFormaterForLogs(currentDate); - logMsgToFile(level, msg, dateForLog); - logThrowableToFile(level, throwable, dateForLog); + private static void logToFile(Level level, @NotNull String tag, @NotNull String msg, @NotNull Throwable throwable) { + if (isLoggable(level)) { + synchronized (lockToWrite) { + final LocalDateTime currentDate = LocalDateTime.now(); + updateAndCreateFile(currentDate); + final String dateForLog = dateFormatterForLogs(currentDate); + logMsgToFile(level, tag, msg, dateForLog); + logThrowableToFile(level, tag, throwable, dateForLog); + } } } - private void logMsgToFile(Level level, String msg, String dateForLog) { - dateForLog += " [" + logger.getName() + "]" + level.toString() + " - " + msg; - logsToFile.add(dateForLog); + private static void logMsgToFile(@NotNull Level level, @NotNull String tag, @NotNull String msg, @NotNull String dateForLog) { + final String logMessage = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, msg); + logsToFile.add(logMessage); synchronized (logsToFile) { logsToFile.notifyAll(); } } - private void logThrowableToFile(Level level, Throwable throwable, String dateForLog) { - String throwableLog = dateForLog + level.getName() + " - " + throwable + "\n"; + private static void logThrowableToFile(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable, @NotNull String dateForLog) { + String throwableLog = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, throwable.toString()); for (StackTraceElement element : throwable.getStackTrace()) { throwableLog += "\tat " + element + "\n"; } @@ -346,23 +315,16 @@ public class BotLogger { } } - private boolean isLoggable(Level level) { + private static boolean isLoggable(Level level) { return logger.isLoggable(level) && BuildVars.debug; } - @Override - protected void finalize() throws Throwable { - logginFile.flush(); - logginFile.close(); - super.finalize(); - } - private static class LoggerThread extends Thread { + @Override public void run() { - setPriority(Thread.MIN_PRIORITY); while(true) { - ConcurrentLinkedQueue stringsToLog = new ConcurrentLinkedQueue<>(); + final ConcurrentLinkedQueue stringsToLog = new ConcurrentLinkedQueue<>(); synchronized (logsToFile) { if (logsToFile.isEmpty()) { try { @@ -378,9 +340,7 @@ public class BotLogger { logsToFile.clear(); } - for (String stringToLog: stringsToLog) { - logginFile.println(stringToLog); - } + stringsToLog.stream().forEach(logginFile::println); logginFile.flush(); } } diff --git a/src/main/java/org/telegram/services/DirectionsService.java b/src/main/java/org/telegram/services/DirectionsService.java index 20f750b..305a651 100644 --- a/src/main/java/org/telegram/services/DirectionsService.java +++ b/src/main/java/org/telegram/services/DirectionsService.java @@ -13,7 +13,6 @@ import org.json.JSONObject; import org.jsoup.Jsoup; import org.telegram.BuildVars; -import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.time.format.DateTimeFormatter; @@ -27,7 +26,7 @@ import java.util.List; * @date 20 of June of 2015 */ public class DirectionsService { - private static volatile BotLogger log = BotLogger.getLogger(DirectionsService.class.getName()); + private static final String LOGTAG = "DIRECTIONSSERVICE"; private static final String BASEURL = "https://maps.googleapis.com/maps/api/directions/json"; ///< Base url for REST private static final String APIIDEND = "&key=" + BuildVars.DirectionsApiKey; @@ -98,7 +97,7 @@ public class DirectionsService { responseToUser.add(LocalisationService.getInstance().getString("directionsNotFound", language)); } } catch (Exception e) { - log.warning(e); + BotLogger.warn(LOGTAG, e); responseToUser.add(LocalisationService.getInstance().getString("errorFetchingDirections", language)); } return responseToUser; diff --git a/src/main/java/org/telegram/services/LocalisationService.java b/src/main/java/org/telegram/services/LocalisationService.java index 53e923f..48161f0 100644 --- a/src/main/java/org/telegram/services/LocalisationService.java +++ b/src/main/java/org/telegram/services/LocalisationService.java @@ -3,7 +3,10 @@ package org.telegram.services; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; /** * @author Ruben Bermudez @@ -31,6 +34,7 @@ public class LocalisationService { private ResourceBundle galician; private ResourceBundle persian; private ResourceBundle turkish; + private ResourceBundle esperanto; private class CustomClassLoader extends ClassLoader { public CustomClassLoader(ClassLoader parent) { @@ -92,6 +96,8 @@ public class LocalisationService { supportedLanguages.put("nl", "Nederlands"); italian = ResourceBundle.getBundle("localisation.strings", new Locale("it", "IT"), loader); supportedLanguages.put("it", "Italiano"); + esperanto = ResourceBundle.getBundle("localisation.strings", new Locale("eo", "EO"), loader); + supportedLanguages.put("eo", "Esperanto"); /* german = ResourceBundle.getBundle("localisation.strings", new Locale("de", "DE"), loader); supportedLanguages.put("de", "Deutsch"); @@ -155,6 +161,9 @@ public class LocalisationService { case "it": result = italian.getString(key); break; + case "eo": + result = esperanto.getString(key); + break; /*case "de": result = german.getString(key); break; diff --git a/src/main/java/org/telegram/services/RaeService.java b/src/main/java/org/telegram/services/RaeService.java new file mode 100644 index 0000000..7272a21 --- /dev/null +++ b/src/main/java/org/telegram/services/RaeService.java @@ -0,0 +1,231 @@ +package org.telegram.services; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.entity.BufferedHttpEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; +import org.jsoup.select.Elements; + +import java.io.IOException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Rae service + * @date 20 of June of 2015 + */ +public class RaeService { + private static final String LOGTAG = "RAESERVICE"; + + private static final String BASEURL = "http://dle.rae.es/srv/"; ///< Base url for REST + private static final String SEARCHEXACTURL = "search?m=30&w="; + private static final String SEARCHWORDURL = "search?m=form&w="; + private static final String WORDLINKBYID = "http://dle.rae.es/?id="; + + + public List getResults(String query) { + List results = new ArrayList<>(); + + String completeURL; + try { + completeURL = BASEURL + SEARCHEXACTURL + URLEncoder.encode(query, "UTF-8"); + + CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + HttpGet request = new HttpGet(completeURL); + + CloseableHttpResponse response = client.execute(request); + HttpEntity ht = response.getEntity(); + + BufferedHttpEntity buf = new BufferedHttpEntity(ht); + String responseString = EntityUtils.toString(buf, "UTF-8"); + + Document document = Jsoup.parse(responseString); + Element article = document.getElementsByTag("article").first(); + String articleId = null; + if (article != null) { + articleId = article.attributes().get("id"); + } + Elements elements = document.select(".j"); + + if (elements.isEmpty()) { + results = getResultsWordSearch(query); + } else { + results = getResultsFromExactMatch(elements, query, articleId); + } + } catch (IOException e) { + BotLogger.error(LOGTAG, e); + } + + return results; + } + + private List getResultsWordSearch(String query) { + List results = new ArrayList<>(); + + String completeURL; + try { + completeURL = BASEURL + SEARCHWORDURL + URLEncoder.encode(query, "UTF-8"); + + CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + HttpGet request = new HttpGet(completeURL); + + CloseableHttpResponse response = client.execute(request); + HttpEntity ht = response.getEntity(); + + BufferedHttpEntity buf = new BufferedHttpEntity(ht); + String responseString = EntityUtils.toString(buf, "UTF-8"); + + Document document = Jsoup.parse(responseString); + Element list = document.select("body div ul").first(); + + if (list != null) { + Elements links = list.getElementsByTag("a"); + if (!links.isEmpty()) { + for (Element link : links) { + List partialResults = fetchWord(link.attributes().get("href"), link.text()); + if (!partialResults.isEmpty()) { + results.addAll(partialResults); + } + } + } + } + } catch (IOException e) { + BotLogger.error(LOGTAG, e); + } + + return results; + } + + private List fetchWord(String link, String word) { + List results = new ArrayList<>(); + + String completeURL; + try { + completeURL = BASEURL + link; + + CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + HttpGet request = new HttpGet(completeURL); + + CloseableHttpResponse response = client.execute(request); + HttpEntity ht = response.getEntity(); + + BufferedHttpEntity buf = new BufferedHttpEntity(ht); + String responseString = EntityUtils.toString(buf, "UTF-8"); + + Document document = Jsoup.parse(responseString); + Element article = document.getElementsByTag("article").first(); + String articleId = null; + if (article != null) { + articleId = article.attributes().get("id"); + } + Elements elements = document.select(".j"); + + if (!elements.isEmpty()) { + results = getResultsFromExactMatch(elements, word, articleId); + } + } catch (IOException e) { + BotLogger.error(LOGTAG, e); + } + + return results; + } + + private List getResultsFromExactMatch(Elements elements, String word, String link) { + List results = new ArrayList<>(); + for (int i = 0; i < elements.size(); i++) { + Element element = elements.get(i); + RaeResult result = new RaeResult(); + if (link != null && !link.isEmpty()) { + result.link = WORDLINKBYID + link; + } + result.index = i; + result.word = capitalizeFirstLetter(word); + Elements tags = element.getElementsByTag("abbr"); + tags.removeIf(x -> !x.parent().equals(element)); + for (Element tag : tags) { + result.tags.put(tag.text(), tag.attributes().get("title")); + } + Elements definition = element.getElementsByTag("mark"); + definition.removeIf(x -> !x.parent().equals(element)); + if (definition.isEmpty()) { + results.addAll(findResultsFromRedirect(element, word)); + } else { + StringBuilder definitionBuilder = new StringBuilder(); + definition.stream().forEachOrdered(y -> { + String partialText = y.text(); + if (definitionBuilder.length() > 0) { + definitionBuilder.append(" "); + partialText = partialText.toLowerCase(); + } + definitionBuilder.append(partialText); + }); + result.definition = capitalizeFirstLetter(definitionBuilder.toString()); + results.add(result); + } + } + + return results; + } + + private List findResultsFromRedirect(Element element, String word) { + List results = new ArrayList<>(); + Element redirect = element.getElementsByTag("a").first(); + if (redirect != null) { + String link = redirect.attributes().get("href"); + results = fetchWord(link, word); + } + + return results; + } + + private static String capitalizeFirstLetter(String original) { + if (original == null || original.length() == 0) { + return original; + } + return original.substring(0, 1).toUpperCase() + original.substring(1); + } + + public static class RaeResult { + public int index; + public String word; + public Map tags = new HashMap<>(); + public String definition; + public String link; + + public String getDefinition() { + final StringBuilder builder = new StringBuilder(); + if (link != null && !link.isEmpty()) { + builder.append("[").append(word).append("]("); + builder.append(link).append(")\n"); + } + for (Map.Entry tag : tags.entrySet()) { + builder.append("*").append(tag.getKey()).append("*"); + builder.append(" (_").append(tag.getValue()).append("_)\n"); + } + builder.append(definition); + return builder.toString(); + } + + public String getDescription() { + return definition; + } + + public String getTitle() { + final StringBuilder builder = new StringBuilder(); + builder.append(index).append(". ").append(word); + return builder.toString(); + } + } +} diff --git a/src/main/java/org/telegram/services/TimerExecutor.java b/src/main/java/org/telegram/services/TimerExecutor.java index 1f87ce4..278313e 100644 --- a/src/main/java/org/telegram/services/TimerExecutor.java +++ b/src/main/java/org/telegram/services/TimerExecutor.java @@ -1,6 +1,8 @@ package org.telegram.services; -import java.time.*; +import java.time.Clock; +import java.time.Duration; +import java.time.LocalDateTime; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -12,7 +14,7 @@ import java.util.concurrent.TimeUnit; * @date 27/01/25 */ public class TimerExecutor { - private static volatile BotLogger log = BotLogger.getLogger(TimerExecutor.class.getName()); + private static final String LOGTAG = "TIMEREXECUTOR"; private static volatile TimerExecutor instance; ///< Instance private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); ///< Thread to execute operations @@ -52,14 +54,14 @@ public class TimerExecutor { * @param targetSec Second to execute it */ public void startExecutionEveryDayAt(CustomTimerTask task, int targetHour, int targetMin, int targetSec) { - log.warn("Posting new task" + task.getTaskName()); + BotLogger.warn(LOGTAG, "Posting new task" + task.getTaskName()); final Runnable taskWrapper = () -> { try { task.execute(); task.reduceTimes(); startExecutionEveryDayAt(task, targetHour, targetMin, targetSec); } catch (Exception e) { - log.severe("Bot threw an unexpected exception at TimerExecutor", e); + BotLogger.severe(LOGTAG, "Bot threw an unexpected exception at TimerExecutor", e); } }; if (task.getTimes() != 0) { @@ -100,9 +102,9 @@ public class TimerExecutor { try { executorService.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException ex) { - log.severe(ex); + BotLogger.severe(LOGTAG, ex); } catch (Exception e) { - log.severe("Bot threw an unexpected exception at TimerExecutor", e); + BotLogger.severe(LOGTAG, "Bot threw an unexpected exception at TimerExecutor", e); } } } diff --git a/src/main/java/org/telegram/services/TransifexService.java b/src/main/java/org/telegram/services/TransifexService.java index 1c7e2bb..3f9883c 100644 --- a/src/main/java/org/telegram/services/TransifexService.java +++ b/src/main/java/org/telegram/services/TransifexService.java @@ -19,7 +19,7 @@ import java.io.*; * @date 21 of June of 2015 */ public class TransifexService { - private static volatile BotLogger log = BotLogger.getLogger(TransifexService.class.getName()); + private static final String LOGTAG = "TRANSIFEXSERVICE"; private static final String BASEURLAndroid = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/telegram/resource/stringsxml-48/translation/@language?file"; ///< Base url for REST private static final String BASEURLiOS = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/iphone-1/resource/localizablestrings/translation/@language?file"; ///< Base url for REST @@ -76,7 +76,7 @@ public class TransifexService { result = responseString; } } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return result; } @@ -89,7 +89,7 @@ public class TransifexService { HttpResponse response = client.execute(request); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return result; } @@ -102,7 +102,7 @@ public class TransifexService { HttpResponse response = client.execute(request); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return result; } @@ -115,7 +115,7 @@ public class TransifexService { HttpResponse response = client.execute(request); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return result; } @@ -128,7 +128,7 @@ public class TransifexService { HttpResponse response = client.execute(request); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return result; } @@ -141,7 +141,7 @@ public class TransifexService { HttpResponse response = client.execute(request); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return result; } @@ -154,7 +154,7 @@ public class TransifexService { HttpResponse response = client.execute(request); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return result; } @@ -194,11 +194,11 @@ public class TransifexService { sendDocument = new SendDocument(); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); } catch (FileNotFoundException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } } catch (Exception e) { - log.error(e); + BotLogger.error(LOGTAG, e); } return sendDocument; } @@ -221,11 +221,11 @@ public class TransifexService { sendDocument = new SendDocument(); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); } catch (FileNotFoundException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } } catch (Exception e) { - e.printStackTrace(); + BotLogger.error(LOGTAG, e); } return sendDocument; } @@ -249,11 +249,11 @@ public class TransifexService { sendDocument = new SendDocument(); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); } catch (IOException e) { - e.printStackTrace(); + BotLogger.error(LOGTAG, e); } } } catch (Exception e) { - e.printStackTrace(); + BotLogger.error(LOGTAG, e); } return sendDocument; } @@ -276,11 +276,11 @@ public class TransifexService { sendDocument = new SendDocument(); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); } catch (IOException e) { - e.printStackTrace(); + BotLogger.error(LOGTAG, e); } } } catch (Exception e) { - e.printStackTrace(); + BotLogger.error(LOGTAG, e); } return sendDocument; } diff --git a/src/main/java/org/telegram/services/WeatherService.java b/src/main/java/org/telegram/services/WeatherService.java index d96c1d0..880a92a 100644 --- a/src/main/java/org/telegram/services/WeatherService.java +++ b/src/main/java/org/telegram/services/WeatherService.java @@ -26,7 +26,7 @@ import java.time.format.DateTimeFormatter; * @date 20 of June of 2015 */ public class WeatherService { - private static volatile BotLogger log = BotLogger.getLogger(WeatherService.class.getName()); + private static final String LOGTAG = "WEATHERSERVICE"; public static final String METRICSYSTEM = "metric"; public static final String IMPERIALSYSTEM = "imperial"; @@ -90,7 +90,7 @@ public class WeatherService { String responseString = EntityUtils.toString(buf, "UTF-8"); JSONObject jsonObject = new JSONObject(responseString); - log.warning(jsonObject.toString()); + BotLogger.info(LOGTAG, jsonObject.toString()); if (jsonObject.getInt("cod") == 200) { cityFound = jsonObject.getJSONObject("city").getString("name") + " (" + jsonObject.getJSONObject("city").getString("country") + ")"; @@ -98,11 +98,11 @@ public class WeatherService { responseToUser = String.format(LocalisationService.getInstance().getString("weatherAlert", language), cityFound, convertListOfForecastToString(jsonObject, language, units, false)); } else { - log.warning(jsonObject.toString()); + BotLogger.warn(LOGTAG, jsonObject.toString()); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); } } catch (Exception e) { - log.error(e); + BotLogger.error(LOGTAG, e); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); } return responseToUser; @@ -131,7 +131,7 @@ public class WeatherService { String responseString = EntityUtils.toString(buf, "UTF-8"); JSONObject jsonObject = new JSONObject(responseString); - log.warning(jsonObject.toString()); + BotLogger.info(LOGTAG, jsonObject.toString()); if (jsonObject.getInt("cod") == 200) { cityFound = jsonObject.getJSONObject("city").getString("name") + " (" + jsonObject.getJSONObject("city").getString("country") + ")"; @@ -139,11 +139,11 @@ public class WeatherService { responseToUser = String.format(LocalisationService.getInstance().getString("weatherForcast", language), cityFound, convertListOfForecastToString(jsonObject, language, units, true)); } else { - log.warning(jsonObject.toString()); + BotLogger.warn(LOGTAG, jsonObject.toString()); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); } } catch (Exception e) { - log.error(e); + BotLogger.error(LOGTAG, e); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); } return responseToUser; @@ -178,11 +178,11 @@ public class WeatherService { responseToUser = String.format(LocalisationService.getInstance().getString("weatherForcast", language), cityFound, convertListOfForecastToString(jsonObject, language, units, true)); } else { - log.warning(jsonObject.toString()); + BotLogger.warn(LOGTAG, jsonObject.toString()); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); } } catch (Exception e) { - log.error(e); + BotLogger.error(LOGTAG, e); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); } return responseToUser; @@ -219,11 +219,11 @@ public class WeatherService { responseToUser = String.format(LocalisationService.getInstance().getString("weatherCurrent", language), cityFound, convertCurrentWeatherToString(jsonObject, language, units, emoji)); } else { - log.warning(jsonObject.toString()); + BotLogger.warn(LOGTAG, jsonObject.toString()); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); } } catch (Exception e) { - log.error(e); + BotLogger.error(LOGTAG, e); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); } return responseToUser; @@ -258,11 +258,11 @@ public class WeatherService { responseToUser = String.format(LocalisationService.getInstance().getString("weatherCurrent", language), cityFound, convertCurrentWeatherToString(jsonObject, language, units, null)); } else { - log.warning(jsonObject.toString()); + BotLogger.warn(LOGTAG, jsonObject.toString()); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); } } catch (Exception e) { - log.error(e); + BotLogger.error(LOGTAG, e); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); } return responseToUser; diff --git a/src/main/java/org/telegram/updateshandlers/ChannelHandlers.java b/src/main/java/org/telegram/updateshandlers/ChannelHandlers.java new file mode 100644 index 0000000..4d6790d --- /dev/null +++ b/src/main/java/org/telegram/updateshandlers/ChannelHandlers.java @@ -0,0 +1,184 @@ +package org.telegram.updateshandlers; + +import org.telegram.BotConfig; +import org.telegram.BuildVars; +import org.telegram.SenderHelper; +import org.telegram.api.methods.BotApiMethod; +import org.telegram.api.methods.SendMessage; +import org.telegram.api.objects.ForceReplyKeyboard; +import org.telegram.api.objects.Message; +import org.telegram.api.objects.ReplyKeyboardMarkup; +import org.telegram.api.objects.Update; +import org.telegram.services.BotLogger; +import org.telegram.updatesreceivers.UpdatesThread; +import org.telegram.updatesreceivers.Webhook; + +import java.io.InvalidObjectException; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Handler for updates to channel updates bot + * This is a use case that will send a message to a channel if it is added as an admin to it. + * @date 24 of June of 2015 + */ +public class ChannelHandlers implements UpdatesCallback { + private static final String LOGTAG = "CHANNELHANDLERS"; + private static final String TOKEN = BotConfig.TOKENCHANNEL; + private static final String BOTNAME = BotConfig.USERNAMECHANNEL; + private static final boolean USEWEBHOOK = false; + + private static final int WAITINGCHANNEL = 1; + + private static final String HELP_TEXT = "Send me the channel username where you added me as admin."; + private static final String CANCEL_COMMAND = "/stop"; + private static final String AFTER_CHANNEL_TEXT = "A message to provided channel will be sent if the bot was added to it as admin."; + private static final String WRONG_CHANNEL_TEXT = "Wrong username, please remember to add *@* before the username and send only the username."; + private static final String CHANNEL_MESSAGE_TEXT = "This message was sent by *@updateschannelbot*. Enjoy!"; + private static final String ERROR_MESSAGE_TEXT = "There was an error sending the message to channel *%s*, the error was: ```%s```"; + + private final ConcurrentHashMap userState = new ConcurrentHashMap<>(); + + private final Object webhookLock = new Object(); + + public ChannelHandlers(Webhook webhook) { + if (USEWEBHOOK && BuildVars.useWebHook) { + webhook.registerWebhook(this, BOTNAME); + SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); + } else { + SenderHelper.SendWebhook("", TOKEN); + new UpdatesThread(TOKEN, this); + } + } + + @Override + public void onUpdateReceived(Update update) { + Message message = update.getMessage(); + if (message != null && message.hasText()) { + try { + BotApiMethod botApiMethod = handleIncomingMessage(message); + if (botApiMethod != null) { + SenderHelper.SendApiMethod(botApiMethod, TOKEN); + } + } catch (InvalidObjectException e) { + BotLogger.severe(LOGTAG, e); + } + } + } + + @Override + public BotApiMethod onWebhookUpdateReceived(Update update) { + throw new NoSuchMethodError(); + } + + + // region Incoming messages handlers + + private BotApiMethod handleIncomingMessage(Message message) throws InvalidObjectException { + int state = userState.getOrDefault(message.getFrom().getId(), 0); + BotApiMethod botApiMethod; + switch(state) { + case WAITINGCHANNEL: + botApiMethod = onWaitingChannelMessage(message); + break; + default: + botApiMethod = sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null); + userState.put(message.getFrom().getId(), WAITINGCHANNEL); + break; + } + return botApiMethod; + } + + private BotApiMethod onWaitingChannelMessage(Message message) throws InvalidObjectException { + BotApiMethod sendMessage = null; + if (message.getText().equals(CANCEL_COMMAND)) { + userState.remove(message.getFrom().getId()); + sendMessage = sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null); + } else { + if (message.getText().startsWith("@") && !message.getText().trim().contains(" ")) { + sendBuiltMessage(getMessageToChannelSent(message)); + sendMessageToChannel(message.getText(), message); + userState.remove(message.getFrom().getId()); + } else { + sendMessage = getWrongUsernameMessage(message); + } + } + + return sendMessage; + } + + private static void sendMessageToChannel(String username, Message message) { + SendMessage sendMessage = new SendMessage(); + sendMessage.enableMarkdown(true); + sendMessage.setChatId(username.trim()); + + sendMessage.setText(CHANNEL_MESSAGE_TEXT); + sendMessage.enableMarkdown(true); + + try { + sendBuiltMessage(sendMessage); + } catch (InvalidObjectException e) { + sendErrorMessage(message, e.getMessage()); + } + } + + private static void sendErrorMessage(Message message, String errorText) { + SendMessage sendMessage = new SendMessage(); + sendMessage.enableMarkdown(true); + sendMessage.setChatId(message.getChatId().toString()); + sendMessage.setReplayToMessageId(message.getMessageId()); + + sendMessage.setText(String.format(ERROR_MESSAGE_TEXT, message.getText().trim(), errorText.replace("\"", "\\\""))); + sendMessage.enableMarkdown(true); + + try { + sendBuiltMessage(sendMessage); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } + } + + private static BotApiMethod getWrongUsernameMessage(Message message) { + SendMessage sendMessage = new SendMessage(); + sendMessage.enableMarkdown(true); + sendMessage.setChatId(message.getChatId().toString()); + sendMessage.setReplayToMessageId(message.getMessageId()); + + ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); + forceReplyKeyboard.setSelective(true); + forceReplyKeyboard.setForceReply(true); + sendMessage.setReplayMarkup(forceReplyKeyboard); + + sendMessage.setText(WRONG_CHANNEL_TEXT); + sendMessage.enableMarkdown(true); + return sendMessage; + } + + private static SendMessage getMessageToChannelSent(Message message) { + SendMessage sendMessage = new SendMessage(); + sendMessage.enableMarkdown(true); + sendMessage.setChatId(message.getChatId().toString()); + sendMessage.setReplayToMessageId(message.getMessageId()); + + sendMessage.setText(AFTER_CHANNEL_TEXT); + return sendMessage; + } + + private static BotApiMethod sendHelpMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup) { + SendMessage sendMessage = new SendMessage(); + sendMessage.enableMarkdown(true); + sendMessage.setChatId(chatId); + sendMessage.setReplayToMessageId(messageId); + if (replyKeyboardMarkup != null) { + sendMessage.setReplayMarkup(replyKeyboardMarkup); + } + + sendMessage.setText(HELP_TEXT); + return sendMessage; + } + + private static void sendBuiltMessage(SendMessage sendMessage) throws InvalidObjectException { + SenderHelper.SendApiMethod(sendMessage, TOKEN); + } +} diff --git a/src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java b/src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java index 38658f2..d7811d9 100644 --- a/src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java +++ b/src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java @@ -1,16 +1,21 @@ package org.telegram.updateshandlers; import org.json.JSONObject; -import org.telegram.*; -import org.telegram.api.objects.*; -import org.telegram.database.DatabaseManager; +import org.telegram.BotConfig; +import org.telegram.BuildVars; +import org.telegram.Commands; +import org.telegram.SenderHelper; import org.telegram.api.methods.BotApiMethod; import org.telegram.api.methods.SendMessage; +import org.telegram.api.objects.*; +import org.telegram.database.DatabaseManager; +import org.telegram.services.BotLogger; import org.telegram.services.DirectionsService; import org.telegram.services.LocalisationService; import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.Webhook; +import java.io.InvalidObjectException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -24,6 +29,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; * @date 24 of June of 2015 */ public class DirectionsHandlers implements UpdatesCallback { + private static final String LOGTAG = "DIRECTIONSHANDLERS"; private static final String TOKEN = BotConfig.TOKENDIRECTIONS; private static final String BOTNAME = BotConfig.USERNAMEDIRECTIONS; private static final boolean USEWEBHOOK = false; @@ -33,7 +39,7 @@ public class DirectionsHandlers implements UpdatesCallback { private final ConcurrentLinkedQueue languageMessages = new ConcurrentLinkedQueue<>(); public DirectionsHandlers(Webhook webhook) { - if (USEWEBHOOK) { + if (USEWEBHOOK && BuildVars.useWebHook) { webhook.registerWebhook(this, BOTNAME); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); } else { @@ -44,7 +50,11 @@ public class DirectionsHandlers implements UpdatesCallback { @Override public void onUpdateReceived(Update update) { - handleDirections(update); + try { + handleDirections(update); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } } @Override @@ -53,7 +63,7 @@ public class DirectionsHandlers implements UpdatesCallback { return null; } - public void handleDirections(Update update) { + public void handleDirections(Update update) throws InvalidObjectException { Message message = update.getMessage(); if (message != null && message.hasText()) { if (languageMessages.contains(message.getFrom().getId())) { @@ -84,7 +94,7 @@ public class DirectionsHandlers implements UpdatesCallback { } else { SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.setText(LocalisationService.getInstance().getString("youNeedReplyDirections", language)); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } } @@ -98,7 +108,7 @@ public class DirectionsHandlers implements UpdatesCallback { String destiny = message.getText(); List directions = DirectionsService.getInstance().getDirections(origin, destiny, language); SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide(); replyKeyboardHide.setSelective(true); sendMessageRequest.setReplayMarkup(replyKeyboardHide); @@ -125,7 +135,7 @@ public class DirectionsHandlers implements UpdatesCallback { private void onOriginReceived(Message message, String language) { SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setReplayToMessageId(message.getMessageId()); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); forceReplyKeyboard.setSelective(true); @@ -149,19 +159,19 @@ public class DirectionsHandlers implements UpdatesCallback { } - private void sendHelpMessage(Message message, String language) { + private void sendHelpMessage(Message message, String language) throws InvalidObjectException { SendMessage sendMessageRequest = new SendMessage(); String helpDirectionsFormated = String.format( LocalisationService.getInstance().getString("helpDirections", language), Commands.startDirectionCommand); sendMessageRequest.setText(helpDirectionsFormated); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } private void onStartdirectionsCommand(Message message, String language) { SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setReplayToMessageId(message.getMessageId()); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); forceReplyKeyboard.setSelective(true); @@ -185,9 +195,9 @@ public class DirectionsHandlers implements UpdatesCallback { } - private void onSetLanguageCommand(Message message, String language) { + private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException { SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); HashMap languages = LocalisationService.getInstance().getSupportedLanguages(); List> commands = new ArrayList<>(); @@ -206,10 +216,10 @@ public class DirectionsHandlers implements UpdatesCallback { languageMessages.add(message.getFrom().getId()); } - private void onLanguageSelected(Message message) { + private void onLanguageSelected(Message message) throws InvalidObjectException { String[] parts = message.getText().split("-->", 2); SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) { DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim()); sendMessageRequest.setText(LocalisationService.getInstance().getString("languageModified", parts[0].trim())); diff --git a/src/main/java/org/telegram/updateshandlers/FilesHandlers.java b/src/main/java/org/telegram/updateshandlers/FilesHandlers.java index 391e249..a30a727 100644 --- a/src/main/java/org/telegram/updateshandlers/FilesHandlers.java +++ b/src/main/java/org/telegram/updateshandlers/FilesHandlers.java @@ -4,19 +4,21 @@ import org.telegram.BotConfig; import org.telegram.BuildVars; import org.telegram.Commands; import org.telegram.SenderHelper; +import org.telegram.api.methods.BotApiMethod; +import org.telegram.api.methods.SendDocument; +import org.telegram.api.methods.SendMessage; import org.telegram.api.objects.Message; import org.telegram.api.objects.ReplyKeyboardHide; import org.telegram.api.objects.ReplyKeyboardMarkup; import org.telegram.api.objects.Update; import org.telegram.database.DatabaseManager; -import org.telegram.api.methods.BotApiMethod; -import org.telegram.api.methods.SendDocument; -import org.telegram.api.methods.SendMessage; +import org.telegram.services.BotLogger; import org.telegram.services.Emoji; import org.telegram.services.LocalisationService; import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.Webhook; +import java.io.InvalidObjectException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -31,6 +33,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; * @date 24 of June of 2015 */ public class FilesHandlers implements UpdatesCallback { + private static final String LOGTAG = "FILESHANDLERS"; private static final String TOKEN = BotConfig.TOKENFILES; private static final String BOTNAME = BotConfig.USERNAMEFILES; private static final boolean USEWEBHOOK = false; @@ -40,7 +43,7 @@ public class FilesHandlers implements UpdatesCallback { private final ConcurrentLinkedQueue languageMessages = new ConcurrentLinkedQueue<>(); public FilesHandlers(Webhook webhook) { - if (USEWEBHOOK) { + if (USEWEBHOOK && BuildVars.useWebHook) { webhook.registerWebhook(this, BOTNAME); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); } else { @@ -51,7 +54,11 @@ public class FilesHandlers implements UpdatesCallback { @Override public void onUpdateReceived(Update update) { - handleFileUpdate(update); + try { + handleFileUpdate(update); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } } @Override @@ -60,7 +67,7 @@ public class FilesHandlers implements UpdatesCallback { return null; } - public void handleFileUpdate(Update update) { + public void handleFileUpdate(Update update) throws InvalidObjectException { Message message = update.getMessage(); if (message != null && message.hasText()) { if (languageMessages.contains(message.getFrom().getId())) { @@ -99,12 +106,12 @@ public class FilesHandlers implements UpdatesCallback { SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.setText(LocalisationService.getInstance().getString("fileUploaded", language) + LocalisationService.getInstance().getString("uploadedFileURL", language) + message.getDocument().getFileId()); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } } - private void onListCommand(Message message, String language) { + private void onListCommand(Message message, String language) throws InvalidObjectException { HashMap files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId()); SendMessage sendMessageRequest = new SendMessage(); if (files.size() > 0) { @@ -117,14 +124,14 @@ public class FilesHandlers implements UpdatesCallback { } else { sendMessageRequest.setText(LocalisationService.getInstance().getString("noFiles", language)); } - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide(); replyKeyboardHide.setHideKeyboard(true); sendMessageRequest.setReplayMarkup(replyKeyboardHide); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } - private void onDeleteCommand(Message message, String language, String[] parts) { + private void onDeleteCommand(Message message, String language, String[] parts) throws InvalidObjectException { if (DatabaseManager.getInstance().getUserStatusForFile(message.getFrom().getId()) == DELETE_UPLOADED_STATUS && parts.length == 2) { onDeleteCommandWithParameters(message, language, parts[1]); @@ -133,11 +140,11 @@ public class FilesHandlers implements UpdatesCallback { } } - private void onDeleteCommandWithoutParameters(Message message, String language) { + private void onDeleteCommandWithoutParameters(Message message, String language) throws InvalidObjectException { DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), DELETE_UPLOADED_STATUS); SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.setText(LocalisationService.getInstance().getString("deleteUploadedFile", language)); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); HashMap files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId()); ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); if (files.size() > 0) { @@ -156,7 +163,7 @@ public class FilesHandlers implements UpdatesCallback { SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } - private void onDeleteCommandWithParameters(Message message, String language, String part) { + private void onDeleteCommandWithParameters(Message message, String language, String part) throws InvalidObjectException { String[] innerParts = part.split(Emoji.LEFT_RIGHT_ARROW.toString(), 2); boolean removed = DatabaseManager.getInstance().deleteFile(innerParts[0].trim()); SendMessage sendMessageRequest = new SendMessage(); @@ -165,55 +172,55 @@ public class FilesHandlers implements UpdatesCallback { } else { sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language)); } - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); } - private void onCancelCommand(Message message, String language) { + private void onCancelCommand(Message message, String language) throws InvalidObjectException { DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.setText(LocalisationService.getInstance().getString("processFinished", language)); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } - private void onUploadCommand(Message message, String language) { + private void onUploadCommand(Message message, String language) throws InvalidObjectException { DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), INITIAL_UPLOAD_STATUS); SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.setText(LocalisationService.getInstance().getString("sendFileToUpload", language)); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } - private void sendHelpMessage(Message message, String language) { + private void sendHelpMessage(Message message, String language) throws InvalidObjectException { SendMessage sendMessageRequest = new SendMessage(); String formatedString = String.format( LocalisationService.getInstance().getString("helpFiles", language), Commands.startCommand, Commands.uploadCommand, Commands.deleteCommand, Commands.listCommand); sendMessageRequest.setText(formatedString); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } - private void onStartWithParameters(Message message, String language, String part) { + private void onStartWithParameters(Message message, String language, String part) throws InvalidObjectException { if (DatabaseManager.getInstance().doesFileExists(part.trim())) { SendDocument sendDocumentRequest = new SendDocument(); sendDocumentRequest.setDocument(part.trim()); - sendDocumentRequest.setChatId(message.getChatId()); + sendDocumentRequest.setChatId(message.getChatId().toString()); SenderHelper.SendDocument(sendDocumentRequest, TOKEN); } else { SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language)); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } } - private void onSetLanguageCommand(Message message, String language) { + private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException { SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); HashMap languages = LocalisationService.getInstance().getSupportedLanguages(); List> commands = new ArrayList<>(); @@ -232,10 +239,10 @@ public class FilesHandlers implements UpdatesCallback { languageMessages.add(message.getFrom().getId()); } - private void onLanguageReceived(Message message) { + private void onLanguageReceived(Message message) throws InvalidObjectException { String[] parts = message.getText().split(Emoji.LEFT_RIGHT_ARROW.toString(), 2); SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) { DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim()); sendMessageRequest.setText(LocalisationService.getInstance().getString("languageModified", parts[0].trim())); diff --git a/src/main/java/org/telegram/updateshandlers/RaeHandlers.java b/src/main/java/org/telegram/updateshandlers/RaeHandlers.java new file mode 100644 index 0000000..c5f75e3 --- /dev/null +++ b/src/main/java/org/telegram/updateshandlers/RaeHandlers.java @@ -0,0 +1,151 @@ +package org.telegram.updateshandlers; + +import org.telegram.BotConfig; +import org.telegram.BuildVars; +import org.telegram.SenderHelper; +import org.telegram.api.methods.AnswerInlineQuery; +import org.telegram.api.methods.BotApiMethod; +import org.telegram.api.methods.SendMessage; +import org.telegram.api.objects.*; +import org.telegram.services.BotLogger; +import org.telegram.services.RaeService; +import org.telegram.updatesreceivers.UpdatesThread; +import org.telegram.updatesreceivers.Webhook; + +import java.io.InvalidObjectException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Handler for inline queries in Raebot + * This is a use case that works with both Webhooks and GetUpdates methods + * @date 24 of June of 2015 + */ +public class RaeHandlers implements UpdatesCallback { + private static final String LOGTAG = "RAEHANDLERS"; + private static final String TOKEN = BotConfig.TOKENRAE; + private static final String BOTNAME = BotConfig.USERNAMERAE; + private static final Integer CACHETIME = 86400; + private static final boolean USEWEBHOOK = true; + private final RaeService raeService; + private final Object webhookLock = new Object(); + private final String THUMBNAILBLUE = "https://lh5.ggpht.com/-kSFHGvQkFivERzyCNgKPIECtIOELfPNWAQdXqQ7uqv2xztxqll4bVibI0oHJYAuAas=w300"; + private static final String helpMessage = "Este bot puede ayudarte a buscar definiciones de palabras según el diccionario de la RAE.\n\n" + + "Funciona automáticamente, no hay necesidad de añadirlo a ningún sitio.\n" + + "Simplemente abre cualquiera de tus chats y escribe `@raebot loquesea` en la zona de escribir mensajes.\n" + + "Finalmente pulsa sobre un resultado para enviarlo." + + "\n\n" + + "Por ejemplo, intenta escribir `@raebot Punto` aquí."; + + public RaeHandlers(Webhook webhook) { + raeService = new RaeService(); + if (USEWEBHOOK && BuildVars.useWebHook) { + webhook.registerWebhook(this, BOTNAME); + SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); + } else { + SenderHelper.SendWebhook("", TOKEN); + new UpdatesThread(TOKEN, this); + } + } + + @Override + public void onUpdateReceived(Update update) { + if (update.hasInlineQuery()) { + BotApiMethod botApiMethod = handleIncomingInlineQuery(update.getInlineQuery()); + try { + SenderHelper.SendApiMethod(botApiMethod, TOKEN); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } + } else if (update.hasMessage() && update.getMessage().isUserMessage()) { + try { + SenderHelper.SendApiMethod(getHelpMessage(update.getMessage()), TOKEN); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } + } + } + + @Override + public BotApiMethod onWebhookUpdateReceived(Update update) { + if (update.hasInlineQuery()) { + synchronized (webhookLock) { + return handleIncomingInlineQuery(update.getInlineQuery()); + } + } else if (update.hasMessage() && update.getMessage().isUserMessage()) { + synchronized (webhookLock) { + return getHelpMessage(update.getMessage()); + } + } + return null; + } + + /** + * For an InlineQuery, results from RAE dictionariy are fetch and returned + * @param inlineQuery InlineQuery recieved + * @return BotApiMethod as response to the inline query + */ + private BotApiMethod handleIncomingInlineQuery(InlineQuery inlineQuery) { + String query = inlineQuery.getQuery(); + BotLogger.debug(LOGTAG, "Searching: " + query); + if (!query.isEmpty()) { + List results = raeService.getResults(query); + return converteResultsToResponse(inlineQuery, results); + } else { + return converteResultsToResponse(inlineQuery, new ArrayList<>()); + } + } + + /** + * Converts resutls from RaeService to an answer to an inline query + * @param inlineQuery Original inline query + * @param results Results from RAE service + * @return AnswerInlineQuery method to answer the query + */ + private BotApiMethod converteResultsToResponse(InlineQuery inlineQuery, List results) { + AnswerInlineQuery answerInlineQuery = new AnswerInlineQuery(); + answerInlineQuery.setInlineQueryId(inlineQuery.getId()); + answerInlineQuery.setCacheTime(CACHETIME); + answerInlineQuery.setResults(convertRaeResults(results)); + return answerInlineQuery; + } + + /** + * Converts results from RaeService to a list of InlineQueryResultArticles + * @param raeResults Results from rae service + * @return List of InlineQueryResult + */ + private List convertRaeResults(List raeResults) { + List results = new ArrayList<>(); + + for (int i = 0; i < raeResults.size(); i++) { + RaeService.RaeResult raeResult = raeResults.get(i); + InlineQueryResultArticle article = new InlineQueryResultArticle(); + article.setDisableWebPagePreview(true); + article.setMarkdown(true); + article.setId(Integer.toString(i)); + article.setMessageText(raeResult.getDefinition()); + article.setTitle(raeResult.getTitle()); + article.setDescription(raeResult.getDescription()); + article.setThumbUrl(THUMBNAILBLUE); + results.add(article); + } + + return results; + } + + /** + * Create a help message when an user try to send messages directly to the bot + * @param message Received message + * @return SendMessage method + */ + public BotApiMethod getHelpMessage(Message message) { + SendMessage sendMessage = new SendMessage(); + sendMessage.setChatId(message.getChatId().toString()); + sendMessage.enableMarkdown(true); + sendMessage.setText(helpMessage); + return sendMessage; + } +} diff --git a/src/main/java/org/telegram/updateshandlers/TransifexHandlers.java b/src/main/java/org/telegram/updateshandlers/TransifexHandlers.java index c7e1cd6..fba2bed 100644 --- a/src/main/java/org/telegram/updateshandlers/TransifexHandlers.java +++ b/src/main/java/org/telegram/updateshandlers/TransifexHandlers.java @@ -1,17 +1,23 @@ package org.telegram.updateshandlers; -import org.telegram.*; -import org.telegram.api.objects.Message; -import org.telegram.api.objects.Update; -import org.telegram.database.DatabaseManager; +import org.telegram.BotConfig; +import org.telegram.BuildVars; +import org.telegram.Commands; +import org.telegram.SenderHelper; import org.telegram.api.methods.BotApiMethod; import org.telegram.api.methods.SendDocument; import org.telegram.api.methods.SendMessage; +import org.telegram.api.objects.Message; +import org.telegram.api.objects.Update; +import org.telegram.database.DatabaseManager; +import org.telegram.services.BotLogger; import org.telegram.services.LocalisationService; import org.telegram.services.TransifexService; import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.Webhook; +import java.io.InvalidObjectException; + /** * @author Ruben Bermudez * @version 1.0 @@ -19,12 +25,13 @@ import org.telegram.updatesreceivers.Webhook; * @date 24 of June of 2015 */ public class TransifexHandlers implements UpdatesCallback { + private static final String LOGTAG = "TRANSIFEXHANDLERS"; private static final String TOKEN = BotConfig.TOKENTRANSIFEX; private static final String BOTNAME = BotConfig.USERNAMETRANSIFEX; private static final boolean USEWEBHOOK = false; public TransifexHandlers(Webhook webhook) { - if (USEWEBHOOK) { + if (USEWEBHOOK && BuildVars.useWebHook) { webhook.registerWebhook(this, BOTNAME); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); } else { @@ -35,7 +42,11 @@ public class TransifexHandlers implements UpdatesCallback { @Override public void onUpdateReceived(Update update) { - sendTransifexFile(update); + try { + sendTransifexFile(update); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } } @Override @@ -44,7 +55,7 @@ public class TransifexHandlers implements UpdatesCallback { return null; } - public void sendTransifexFile(Update update) { + public void sendTransifexFile(Update update) throws InvalidObjectException { Message message = update.getMessage(); if (message != null && message.hasText()) { String language = DatabaseManager.getInstance().getUserLanguage(update.getMessage().getFrom().getId()); @@ -74,12 +85,12 @@ public class TransifexHandlers implements UpdatesCallback { Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP, Commands.transifexAndroidSupportCommand); sendMessageRequest.setText(helpFormated); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } if (sendDocument != null) { - sendDocument.setChatId(message.getChatId()); + sendDocument.setChatId(message.getChatId().toString()); SenderHelper.SendDocument(sendDocument, TOKEN); } } else if (parts[0].startsWith(Commands.help) || @@ -91,7 +102,7 @@ public class TransifexHandlers implements UpdatesCallback { Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP, Commands.transifexAndroidSupportCommand); sendMessageRequest.setText(helpFormated); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); } } diff --git a/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java b/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java index 8f88009..553655e 100644 --- a/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java +++ b/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java @@ -4,15 +4,16 @@ import org.telegram.BotConfig; import org.telegram.BuildVars; import org.telegram.Commands; import org.telegram.SenderHelper; -import org.telegram.api.objects.*; -import org.telegram.database.DatabaseManager; import org.telegram.api.methods.BotApiMethod; import org.telegram.api.methods.SendMessage; +import org.telegram.api.objects.*; +import org.telegram.database.DatabaseManager; import org.telegram.services.*; import org.telegram.structure.WeatherAlert; import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.Webhook; +import java.io.InvalidObjectException; import java.util.ArrayList; import java.util.List; @@ -24,6 +25,7 @@ import java.util.List; * @date 24 of June of 2015 */ public class WeatherHandlers implements UpdatesCallback { + private static final String LOGTAG = "WEATHERHANDLERS"; private static final String TOKEN = BotConfig.TOKENWEATHER; private static final String BOTNAME = BotConfig.USERNAMEWEATHER; private static final boolean USEWEBHOOK = true; @@ -46,7 +48,7 @@ public class WeatherHandlers implements UpdatesCallback { private final Object webhookLock = new Object(); public WeatherHandlers(Webhook webhook) { - if (USEWEBHOOK) { + if (USEWEBHOOK && BuildVars.useWebHook) { webhook.registerWebhook(this, BOTNAME); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); } else { @@ -75,12 +77,19 @@ public class WeatherHandlers implements UpdatesCallback { private static void sendAlerts() { List allAlerts = DatabaseManager.getInstance().getAllAlerts(); for (WeatherAlert weatherAlert : allAlerts) { + synchronized (Thread.currentThread()) { + try { + Thread.currentThread().wait(35); + } catch (InterruptedException e) { + BotLogger.severe(LOGTAG, e); + } + } String[] userOptions = DatabaseManager.getInstance().getUserWeatherOptions(weatherAlert.getUserId()); String weather = WeatherService.getInstance().fetchWeatherAlert(weatherAlert.getCityId(), weatherAlert.getUserId(), userOptions[0], userOptions[1]); SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(weatherAlert.getUserId()); + sendMessage.setChatId(String.valueOf(weatherAlert.getUserId())); sendMessage.setText(weather); sendBuiltMessage(sendMessage); } @@ -88,17 +97,23 @@ public class WeatherHandlers implements UpdatesCallback { @Override public void onUpdateReceived(Update update) { - Message message = update.getMessage(); - if (message != null) { - BotApiMethod botApiMethod = handleIncomingMessage(message); - SenderHelper.SendApiMethod(botApiMethod, TOKEN); + if (update.hasMessage()) { + Message message = update.getMessage(); + if (message.hasText() || message.hasLocation()) { + BotApiMethod botApiMethod = handleIncomingMessage(message); + try { + SenderHelper.SendApiMethod(botApiMethod, TOKEN); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } + } } } @Override public BotApiMethod onWebhookUpdateReceived(Update update) { - Message message = update.getMessage(); - if (message != null) { + if (update.hasMessage()) { + Message message = update.getMessage(); synchronized (webhookLock) { return handleIncomingMessage(message); } @@ -106,9 +121,9 @@ public class WeatherHandlers implements UpdatesCallback { return null; } - private static BotApiMethod onCancelCommand(Integer chatId, Integer userId, Integer messageId, ReplyKeyboard replyKeyboard, String language) { + private static BotApiMethod onCancelCommand(Long chatId, Integer userId, Integer messageId, ReplyKeyboard replyKeyboard, String language) { SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chatId.toString()); sendMessage.enableMarkdown(true); sendMessage.setReplayMarkup(getMainMenuKeyboard(language)); sendMessage.setReplayToMessageId(messageId); @@ -124,7 +139,7 @@ public class WeatherHandlers implements UpdatesCallback { private static BotApiMethod handleIncomingMessage(Message message) { final int state = DatabaseManager.getInstance().getWeatherState(message.getFrom().getId(), message.getChatId()); final String language = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[0]; - if (message.isGroupMessage() && message.hasText()) { + if (!message.isUserMessage() && message.hasText()) { if (isCommandForOther(message.getText())) { return null; } else if (message.getText().startsWith(Commands.STOPCOMMAND)){ @@ -168,9 +183,9 @@ public class WeatherHandlers implements UpdatesCallback { return botApiMethod; } - private static void sendHideKeyboard(Integer userId, Integer chatId, Integer messageId) { + private static void sendHideKeyboard(Integer userId, Long chatId, Integer messageId) { SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chatId.toString()); sendMessage.enableMarkdown(true); sendMessage.setReplayToMessageId(messageId); sendMessage.setText(Emoji.WAVING_HAND_SIGN.toString()); @@ -180,8 +195,12 @@ public class WeatherHandlers implements UpdatesCallback { replyKeyboardHide.setHideKeyboard(true); sendMessage.setReplayMarkup(replyKeyboardHide); - SenderHelper.SendApiMethod(sendMessage, TOKEN); - DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE); + try { + SenderHelper.SendApiMethod(sendMessage, TOKEN); + DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE); + } catch (InvalidObjectException e) { + BotLogger.error(LOGTAG, e); + } } @@ -231,7 +250,7 @@ public class WeatherHandlers implements UpdatesCallback { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setText(LocalisationService.getInstance().getString("alertDeleted", language)); @@ -243,7 +262,7 @@ public class WeatherHandlers implements UpdatesCallback { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language)); @@ -257,7 +276,7 @@ public class WeatherHandlers implements UpdatesCallback { if (message.getText().equals(getCancelCommand(language))) { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language)); @@ -280,7 +299,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessageRequest.setReplayMarkup(getAlertsKeyboard(language)); sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setText(getChooseNewAlertSetMessage(message.getText(), language)); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); DatabaseManager.getInstance().insertWeatherState(userId, message.getChatId(), ALERT); return sendMessageRequest; @@ -316,7 +335,7 @@ public class WeatherHandlers implements UpdatesCallback { ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setText(getSettingsMessage(language)); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); @@ -327,7 +346,7 @@ public class WeatherHandlers implements UpdatesCallback { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setText(getAlertListMessage(message.getFrom().getId(), language)); @@ -340,7 +359,7 @@ public class WeatherHandlers implements UpdatesCallback { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); ReplyKeyboardMarkup replyKeyboardMarkup = getAlertsListKeyboard(message.getFrom().getId(), language); if (replyKeyboardMarkup != null) { @@ -360,7 +379,7 @@ public class WeatherHandlers implements UpdatesCallback { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayMarkup(getRecentsKeyboard(message.getFrom().getId(), language, false)); sendMessage.setText(LocalisationService.getInstance().getString("chooseNewAlertCity", language)); sendMessage.setReplayToMessageId(message.getMessageId()); @@ -397,7 +416,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessage.enableMarkdown(true); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language)); @@ -410,7 +429,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessage.enableMarkdown(true); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayMarkup(getUnitsKeyboard(language)); sendMessage.setText(getUnitsMessage(message.getFrom().getId(), language)); @@ -423,7 +442,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessage.enableMarkdown(true); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setReplayMarkup(getLanguagesKeyboard(language)); sendMessage.setText(getLanguageMessage(language)); @@ -460,17 +479,17 @@ public class WeatherHandlers implements UpdatesCallback { ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setText(getSettingsMessage(language)); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); return sendMessage; } - private static BotApiMethod onUnitsError(Integer chatId, Integer messageId, String language) { + private static BotApiMethod onUnitsError(Long chatId, Integer messageId, String language) { SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.enableMarkdown(true); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); sendMessageRequest.setReplayMarkup(getUnitsKeyboard(language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("errorUnitsNotFound", language)); sendMessageRequest.setReplayToMessageId(messageId); @@ -478,12 +497,12 @@ public class WeatherHandlers implements UpdatesCallback { return sendMessageRequest; } - private static BotApiMethod onUnitsChosen(Integer userId, Integer chatId, Integer messageId, String units, String language) { + private static BotApiMethod onUnitsChosen(Integer userId, Long chatId, Integer messageId, String units, String language) { DatabaseManager.getInstance().putUserWeatherUnitsOption(userId, units); SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.enableMarkdown(true); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); sendMessageRequest.setText(LocalisationService.getInstance().getString("unitsUpdated", language)); sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); @@ -518,17 +537,17 @@ public class WeatherHandlers implements UpdatesCallback { ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setText(getSettingsMessage(language)); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); return sendMessage; } - private static BotApiMethod onLanguageError(Integer chatId, Integer messageId, String language) { + private static BotApiMethod onLanguageError(Long chatId, Integer messageId, String language) { SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.enableMarkdown(true); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); sendMessageRequest.setReplayMarkup(getLanguagesKeyboard(language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("errorLanguageNotFound", language)); sendMessageRequest.setReplayToMessageId(messageId); @@ -536,13 +555,13 @@ public class WeatherHandlers implements UpdatesCallback { return sendMessageRequest; } - private static BotApiMethod onLanguageChosen(Integer userId, Integer chatId, Integer messageId, String language) { + private static BotApiMethod onLanguageChosen(Integer userId, Long chatId, Integer messageId, String language) { String languageCode = LocalisationService.getInstance().getLanguageCodeByName(language); DatabaseManager.getInstance().putUserWeatherLanguageOption(userId, languageCode); SendMessage sendMessageRequest = new SendMessage(); sendMessageRequest.enableMarkdown(true); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); sendMessageRequest.setText(LocalisationService.getInstance().getString("languageUpdated", languageCode)); sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(languageCode)); @@ -597,7 +616,7 @@ public class WeatherHandlers implements UpdatesCallback { } } - private static BotApiMethod onForecastWeatherCityReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { + private static BotApiMethod onForecastWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text); if (cityId != null) { String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; @@ -607,7 +626,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setText(weather); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); return sendMessageRequest; @@ -616,12 +635,12 @@ public class WeatherHandlers implements UpdatesCallback { } } - private static BotApiMethod onLocationForecastWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { + private static BotApiMethod onLocationForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { ForceReplyKeyboard forceReplyKeyboard = getForceReply(); SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chatId.toString()); sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherLocationCommand", language)); @@ -630,12 +649,12 @@ public class WeatherHandlers implements UpdatesCallback { return sendMessage; } - private static BotApiMethod onNewForecastWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { + private static BotApiMethod onNewForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { ForceReplyKeyboard forceReplyKeyboard = getForceReply(); SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chatId.toString()); sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherNewCommand", language)); @@ -699,7 +718,7 @@ public class WeatherHandlers implements UpdatesCallback { } } - private static BotApiMethod onCurrentWeatherCityReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { + private static BotApiMethod onCurrentWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text); if (cityId != null) { String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; @@ -709,7 +728,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setText(weather); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); return sendMessageRequest; } else { @@ -717,12 +736,12 @@ public class WeatherHandlers implements UpdatesCallback { } } - private static BotApiMethod onLocationCurrentWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { + private static BotApiMethod onLocationCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { ForceReplyKeyboard forceReplyKeyboard = getForceReply(); SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chatId.toString()); sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherLocationCommand", language)); @@ -731,12 +750,12 @@ public class WeatherHandlers implements UpdatesCallback { return sendMessage; } - private static BotApiMethod onNewCurrentWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { + private static BotApiMethod onNewCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { ForceReplyKeyboard forceReplyKeyboard = getForceReply(); SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chatId.toString()); sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherNewCommand", language)); @@ -767,7 +786,7 @@ public class WeatherHandlers implements UpdatesCallback { } else if (message.getText().equals(getSettingsCommand(language))) { botApiMethod = onSettingsChoosen(message, language); } else if (message.getText().equals(getRateCommand(language))) { - botApiMethod = sendRateMessage(message.getChatId(), message.getMessageId(), null, language); + botApiMethod = sendRateMessage(message.getChatId().toString(), message.getMessageId(), null, language); } else { botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), getMainMenuKeyboard(language), language); @@ -787,7 +806,7 @@ public class WeatherHandlers implements UpdatesCallback { ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setText(getSettingsMessage(language)); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); @@ -801,7 +820,7 @@ public class WeatherHandlers implements UpdatesCallback { ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); if (replyKeyboardMarkup.getKeyboard().size() > 3) { sendMessage.setText(LocalisationService.getInstance().getString("onForecastCommandFromHistory", language)); } else { @@ -819,7 +838,7 @@ public class WeatherHandlers implements UpdatesCallback { ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayToMessageId(message.getMessageId()); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); if (replyKeyboardMarkup.getKeyboard().size() > 3) { sendMessage.setText(LocalisationService.getInstance().getString("onCurrentCommandFromHistory", language)); } else { @@ -1136,14 +1155,14 @@ public class WeatherHandlers implements UpdatesCallback { private static BotApiMethod sendMessageDefault(Message message, String language) { ReplyKeyboardMarkup replyKeyboardMarkup = getMainMenuKeyboard(language); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); - return sendHelpMessage(message.getChatId(), message.getMessageId(), replyKeyboardMarkup, language); + return sendHelpMessage(message.getChatId().toString(), message.getMessageId(), replyKeyboardMarkup, language); } - private static BotApiMethod sendChooseOptionMessage(Integer chatId, Integer messageId, + private static BotApiMethod sendChooseOptionMessage(Long chatId, Integer messageId, ReplyKeyboard replyKeyboard, String language) { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chatId.toString()); sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayMarkup(replyKeyboard); sendMessage.setText(LocalisationService.getInstance().getString("chooseOption", language)); @@ -1151,7 +1170,7 @@ public class WeatherHandlers implements UpdatesCallback { return sendMessage; } - private static BotApiMethod sendHelpMessage(Integer chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { + private static BotApiMethod sendHelpMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); sendMessage.setChatId(chatId); @@ -1163,7 +1182,7 @@ public class WeatherHandlers implements UpdatesCallback { return sendMessage; } - private static BotApiMethod sendRateMessage(Integer chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { + private static BotApiMethod sendRateMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { SendMessage sendMessage = new SendMessage(); sendMessage.enableMarkdown(true); sendMessage.setChatId(chatId); @@ -1189,13 +1208,13 @@ public class WeatherHandlers implements UpdatesCallback { sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setText(weather); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); return sendMessageRequest; } - private static BotApiMethod onForecastWeatherReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { + private static BotApiMethod onForecastWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String weather = WeatherService.getInstance().fetchWeatherForecast(text, userId, language, unitsSystem); SendMessage sendMessageRequest = new SendMessage(); @@ -1203,7 +1222,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setText(weather); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); return sendMessageRequest; @@ -1218,13 +1237,13 @@ public class WeatherHandlers implements UpdatesCallback { sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setText(weather); - sendMessageRequest.setChatId(message.getChatId()); + sendMessageRequest.setChatId(message.getChatId().toString()); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); return sendMessageRequest; } - private static BotApiMethod onCurrentWeatherReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { + private static BotApiMethod onCurrentWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String weather = WeatherService.getInstance().fetchWeatherCurrent(text, userId, language, unitsSystem); SendMessage sendMessageRequest = new SendMessage(); @@ -1232,7 +1251,7 @@ public class WeatherHandlers implements UpdatesCallback { sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setText(weather); - sendMessageRequest.setChatId(chatId); + sendMessageRequest.setChatId(chatId.toString()); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); return sendMessageRequest; @@ -1243,7 +1262,11 @@ public class WeatherHandlers implements UpdatesCallback { // region Helper Methods private static void sendBuiltMessage(SendMessage sendMessage) { - SenderHelper.SendApiMethod(sendMessage, TOKEN); + try { + SenderHelper.SendApiMethod(sendMessage, TOKEN); + } catch (InvalidObjectException e) { + BotLogger.severe(LOGTAG, e); + } } // endregion Helper Methods diff --git a/src/main/java/org/telegram/updatesreceivers/UpdatesThread.java b/src/main/java/org/telegram/updatesreceivers/UpdatesThread.java index 1562242..e785810 100644 --- a/src/main/java/org/telegram/updatesreceivers/UpdatesThread.java +++ b/src/main/java/org/telegram/updatesreceivers/UpdatesThread.java @@ -13,10 +13,10 @@ import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.telegram.api.objects.Update; -import org.telegram.database.DatabaseManager; import org.telegram.api.methods.Constants; import org.telegram.api.methods.GetUpdates; +import org.telegram.api.objects.Update; +import org.telegram.database.DatabaseManager; import org.telegram.services.BotLogger; import org.telegram.updateshandlers.UpdatesCallback; @@ -32,7 +32,7 @@ import java.util.concurrent.TimeUnit; * @date 20 of June of 2015 */ public class UpdatesThread { - private static volatile BotLogger log = BotLogger.getLogger(UpdatesThread.class.getName()); + private static final String LOGTAG = "UPDATESTHREAD"; private final UpdatesCallback callback; private final ReaderThread readerThread; @@ -67,7 +67,7 @@ public class UpdatesThread { httpPost.addHeader("charset", "UTF-8"); httpPost.setEntity(new StringEntity(request.toJson().toString(), ContentType.APPLICATION_JSON)); HttpResponse response; - log.debug(httpPost.toString()); + BotLogger.debug(LOGTAG, httpPost.toString()); response = httpclient.execute(httpPost); HttpEntity ht = response.getEntity(); @@ -80,7 +80,7 @@ public class UpdatesThread { throw new InvalidObjectException(jsonObject.toString()); } JSONArray jsonArray = jsonObject.getJSONArray("result"); - log.debug(jsonArray.toString()); + BotLogger.debug(LOGTAG, jsonArray.toString()); if (jsonArray.length() != 0) { for (int i = 0; i < jsonArray.length(); i++) { Update update = new Update(jsonArray.getJSONObject(i)); @@ -98,15 +98,15 @@ public class UpdatesThread { this.wait(500); } } catch (InterruptedException e) { - log.error(e); + BotLogger.error(LOGTAG, e); continue; } } } catch (JSONException e) { - log.warning(e); + BotLogger.warn(LOGTAG, e); } } catch (IOException e) { - log.warning(e); + BotLogger.warn(LOGTAG, e); } } } @@ -124,7 +124,7 @@ public class UpdatesThread { try { receivedUpdates.wait(); } catch (InterruptedException e) { - log.error(e); + BotLogger.error(LOGTAG, e); continue; } update = receivedUpdates.pollLast(); @@ -136,7 +136,7 @@ public class UpdatesThread { DatabaseManager.getInstance().putLastUpdate(token, update.getUpdateId()); callback.onUpdateReceived(update); } catch (Exception e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } } diff --git a/src/main/java/org/telegram/updatesreceivers/Webhook.java b/src/main/java/org/telegram/updatesreceivers/Webhook.java index f1a1036..e9a97a0 100644 --- a/src/main/java/org/telegram/updatesreceivers/Webhook.java +++ b/src/main/java/org/telegram/updatesreceivers/Webhook.java @@ -21,7 +21,7 @@ import java.net.URI; * @date 20 of June of 2015 */ public class Webhook { - private static volatile BotLogger log = BotLogger.getLogger(Webhook.class.getName()); + private static final String LOGTAG = "WEBHOOK"; private static final String KEYSTORE_SERVER_FILE = "./keystore_server"; private static final String KEYSTORE_SERVER_PWD = "asdfgh"; @@ -47,7 +47,7 @@ public class Webhook { rc.register(restApi); rc.register(JacksonFeature.class); rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true); - log.error("Internal webhook: " + getBaseURI().toString()); + BotLogger.info(LOGTAG, "Internal webhook: " + getBaseURI().toString()); final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer( getBaseURI(), rc, @@ -56,7 +56,7 @@ public class Webhook { try { grizzlyServer.start(); } catch (IOException e) { - log.error(e); + BotLogger.error(LOGTAG, e); } } diff --git a/src/main/resources/localisation/strings_eo.properties b/src/main/resources/localisation/strings_eo.properties new file mode 100644 index 0000000..f1428ca --- /dev/null +++ b/src/main/resources/localisation/strings_eo.properties @@ -0,0 +1,75 @@ +helpTransifex= \u0108u vi estas suferanto de babela eraro? Provu min por Telegram-tradukaro.\n\nPor ricevi la plej lastatempan Telegram-tradukdosieron por lingvo\: \n|-- %s LINGVOKODO \: Ricevi la plej lastatempan iOS-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Android-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Webogram-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Tdesktop-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan OSX-App-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Windows Phone-tradukon.\n\n2. Por ricevi \u011disdatigitan tradukdosieron por via Android-beta-aplika\u0135o\: \n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Android-beta-tradukon.\n\n(La lingvokodo de Esperanto estas\: eo) +helpFiles= \u0108u vi volas konigi dosieron al piratoj? Bonvolu resti \u0109i tie kun viaj boatoj\!\n\nKonigi dosierojn per ligilo\: \n|-- %s DOSIERIDENTIGILO \: Ricevi dosieron per identigilo.\n|-- %s \: Komenci dosieral\u015duton.\n|-- %s \: Elekti unu de viaj dosieroj por forigi \u011din.\n|-- %s \: Montri liston de viaj al\u015dutitaj dosieroj. +helpDirections= Se mapon mi havus, mi bone voja\u011dus.\n\nPor ricevi veturinstrukcion inter du lokoj\: \n|-- %s \: Komenci ricevi veturinstrukcion +sendFileToUpload= Sendu al mi dosieron kiun vi volas konigi. Certu, ke vi aligos \u011din kiel dosieron, ne kiel bildon a\u016d videon. +fileUploaded= Bone, via dosiero estas al\u015dutita. Sendu tiun ligilon al \u0109iuj ajn, kiujn vi volas kaj ili povos el\u015duti la dosieron\:\n +deleteUploadedFile= Elektu la dosieron, kiun vi volas forigi\: +fileDeleted= La dosiero estis forigita +wrongFileId= Mi beda\u016dras, mi ne povas trovi dosieron per tiu identigilo. A\u016d vi tajperaris a\u016d \u011di estis forigita jam. +listOfFiles= Jen viaj nunaj al\u015dutitaj dosieroj\: +noFiles= Vi ne havas ajnajn al\u015dutitajn dosierojn ankora\u016d. +processFinished= La nuna procezo estas nuligita. +uploadedFileURL= https\://telegram.me/filesbot?start\= +initDirections= Respondu al tiu mesa\u011do per via deirpunkto. +sendDestination= Respondu al tiu mesa\u011do per via destino. +youNeedReplyDirections= Mi beda\u016dras, mi ne povas helpi vin, krom se vi respondas al mia mesa\u011do. +chooselanguage= Elektu lingvon de la listo por \u015dan\u011di \u0109i tiun agordon. +errorLanguage= Mi ne subtenas tiun lingvon a\u016d vi tajperaris. La procezo estas nuligita. +directionsInit= %s trovi\u011das je %s for de %s, kaj necesas %s por alveni tien, sekvante tiun veturinstrukcion\:\n +directionsNotFound= Veturinstrukcio inter %s kaj %s ne estas trovita. +errorFetchingDirections= Mi beda\u016dras, eraro okazis dum ricevado de la veturinstrukcio. +directionsStep= %s dum %s (%s) +languageModified= Via lingvo-agordo estas \u011disdatigita. + + +helpWeatherMessage= Suno a\u016d pluvo, hajlo a\u016d glacio? \u0108u vi volas scii?\nDemandu al mi kaj mi donos la scion al vi\!\n\t\t%s Ricevu la nunan veteron de loko a\u016d urbo\n\t\t%s Ricevu prognozon por 3 tagoj de loko a\u016d urbo\n\t\t%s \u015can\u011du nunajn avertojn\n\t\t%s Elektu lingvon por prognozoj\n\t\t%s Elektu viajn preferitajn unuojn +forecast=%sPrognozo +current=%sNuna +help=%sHelpo +settings=%sAgordoj +cancel=%sNuligi +location=%sLoko +new=%sNova +languages=%sLingvoj +alerts=%sAvertoj +units=%sUnuoj +back=%sReen +delete=%sForigi +showList=%sMontri liston +rateMe=%sKlasifiku min +metricSystem=Metra sistemo +imperialSystem= Imperia sistemo +selectLanguage=Via nuna lingvo estas %s. Elektu lingvon de la listo por \u015dan\u011di \u0109i tiun agordon. +languageUpdated=Via lingvo-agordo estas \u011disdatigita. +errorLanguageNotFound= Mi ne subtenas tiun lingvon a\u016d vi tajperaris. Elektu alian el la listo. +selectUnits=Viaj nunaj unuoj estas %s. Elektu unuojn de la listo por \u015dan\u011di \u0109i tiun agordon. +unitsUpdated=Via unuo-agordo estas \u011disdatigita. +errorUnitsNotFound= Mi ne subtenas tiujn unuojn a\u016d vi tajperaris. Elektu unu de la listo. +onWeatherNewCommand=Sendu al mi la urbon, kiu vin interesas. Uzu la jenan formaton\: URBO,LANDO +onWeatherLocationCommand=Sendu al mi la lokon, kiu vin interesas. +onCurrentCommandFromHistory=Elektu opcion de viaj lastaj petoj, "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi la nunan veteron. +onCurrentCommandWithoutHistory=Elektu "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi la nunan veteron. +onForecastCommandFromHistory=Elektu opcion de viaj lastaj petoj, "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi prognozon por 3 tagoj. +onForecastCommandWithoutHistory=Elektu "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi prognozon por 3 tagoj. +weatherCurrent= La vetero por %s estas\:\n\n %s +currentWeatherPartMetric=\t- Vetero\: %s\n\t- Nubeco\: %s\n\t- Temperaturo\: %s \u00baC\n +currentWeatherPartImperial=\t- Vetero\: %s\n\t- Nubeco\: %s\n\t- Temperaturo\: %s \u00baF\n +weatherForcast= La vetero por %s estos\:\n\n %s +forecastWeatherPartMetric= %s je %s \n\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baC\n\t- Malalta temperaturo\: %s \u00baC\n +forecastWeatherPartImperial= %s je %s \n\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baF\n\t- Malalta temperaturo\: %s \u00baF\n +weatherAlert= La vetero por %s estos\:\n\n %s +alertWeatherPartMetric=\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baC\n\t- Malalta temperaturo\: %s \u00baC\n +alertWeatherPartImperial=\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baF\n\t- Malalta temperaturo\: %s \u00baF\n +chooseOption=Elektu opcion de la menuo. +backToMainMenu=Procezo estas nuligita, reen al la \u0109efa menuo. +onSettingsCommand=Elektu opcion\:\n\t\t%s Lingvoj\: Elektu lingvon por prognozoj\n\t\t%s Unuoj\: Elektu viajn preferitajn unuojn\n\t\t%s Avertoj\: \u015can\u011du tagajn avertojn\n\t\t%s Reen\: Reen al la \u0109efa menuo +alertsMenuMessage=\u0108i tie vi povas administri viajn avertojn a\u016d aldoni novajn avertojn. +chooseNewAlertCity=Por kiu urbo vi volas agordi averton? Elektu opcion de viaj lastaj petoj. +newAlertSaved=%s Via averto por %s estas kreita \u011duste, vi ricevos la veteron dufoje tage. +initialAlertList=Vi havas %d avertojn\:\n\n%s +partialAlertList=%s%s\n +noAlertList=Mi ne povas trovi ajnan averton por vi. +alertDeleted=La elektita averto estas forigita. +cityNotFound= Urbo ne estas trovita +errorFetchingWeather= Mi beda\u016dras, eraro okazis dum ricevado de la vetero. +rateMeMessage=Se vi \u015datas \u0109i tiun roboton, bonvolu klasifikadi \u011din \u0109e https\://telegram.me/storebot?start\=weatherbot