TelegramAPI/src/main/java/de/mrbesen/telegram/MessageBuilder.java

318 lines
7.6 KiB
Java

package de.mrbesen.telegram;
import de.mrbesen.telegram.AsyncHandler.Callback;
import de.mrbesen.telegram.objects.TMessage;
import de.mrbesen.telegram.objects.TReplyMarkup;
import de.mrbesen.telegram.objects.TUser;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MessageBuilder {
private String text;
private Formatting format = Formatting.None;
private boolean silent = false;
private boolean no_web_view = false;
private boolean allow_sending_without_reply = false;
private long receiver_id = 0;
private int reply_to_message_id = 0;
private TReplyMarkup markup = null;
private boolean async = false;
private boolean asyncprio = false;
private Callback<TMessage, ?> callback = null;
private Callback<Throwable, Void> excpt = null;
private Attachment attachmenttype = Attachment.none;
private String attachment = null;
private String caption = null;
private int updates = 0;
private TelegramAPI api = null;
public MessageBuilder(TelegramAPI api) {
this.api = api;
}
public MessageBuilder() { }
public MessageBuilder setReciver(long id) {
receiver_id = id;
return this;
}
public MessageBuilder setReciver(TUser user) {
receiver_id = user.getID();
return this;
}
public MessageBuilder setText(String txt) {
txt = txt.trim();
if(txt.isEmpty()) {
throw new IllegalArgumentException("text is not allowed to be empty");
}
try {
text = URLEncoder.encode(txt, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
public MessageBuilder setFormatting(Formatting form) {
format = form;
return this;
}
public MessageBuilder setSilent(boolean b) {
silent = b;
return this;
}
public MessageBuilder setNoWebView(boolean b) {
no_web_view = b;
return this;
}
public MessageBuilder setMarkup(TReplyMarkup markup) {
this.markup = markup;
return this;
}
public MessageBuilder setReplyTo(TMessage msg) {
if(receiver_id == 0)
setReciver(msg.getChatID());
return setReplyTo(msg.getMessageID());
}
public MessageBuilder setReplyTo(int msgid) {
reply_to_message_id = msgid;
return this;
}
public MessageBuilder setAsync() {
async = true;
return this;
}
public MessageBuilder setAsync(boolean b) {
async = b;
return this;
}
public MessageBuilder setAsyncPrio() {
async = true;
asyncprio = true;
return this;
}
public MessageBuilder setCallback(Callback<TMessage, ?> clb) {
callback = clb;
return this;
}
public MessageBuilder setExceptionHandler(Callback<Throwable, Void> exchndl) {
excpt = exchndl;
return this;
}
public MessageBuilder setAttachment(Attachment type, String cont) {
if(cont == null) {
if(type != Attachment.none) throw new IllegalArgumentException("cont == null requires type == none");
attachmenttype = type;
attachment = null;
return this;
}
if(attachmenttype != Attachment.none) {
throw new IllegalArgumentException("You can only attach one thing!");
}
attachmenttype = type;
try {
attachment = URLEncoder.encode(cont, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
public MessageBuilder setCaption(String text) {
try {
this.caption = URLEncoder.encode(text, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
public MessageBuilder setUpdates(int oldmsgid) {
updates = oldmsgid;
return this;
}
/**
* should fail when a message, thats replyed to is not existent default is true
* @param b
* @return this
*/
public MessageBuilder setFailwithoutReply(boolean b) {
allow_sending_without_reply = !b;
return this;
}
public SendableMessage build() {
if(receiver_id == 0) {
throw new MissingException("Reciver");
}
String optionals = "";
if(format != Formatting.None) {
optionals += "&parse_mode=" + format.getname().toLowerCase();
}
if(reply_to_message_id != 0) {
optionals += "&reply_to_message_id=" + reply_to_message_id;
}
if(markup != null) {
try {
optionals += "&reply_markup=" + URLEncoder.encode(markup.toJSONString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
String attachment = "";
String cmd;
String text = "";
if(attachmenttype != Attachment.none) {
if(caption != null)
attachment = "&caption=" + caption;
attachment += "&" + attachmenttype.name().toLowerCase() + "=" + this.attachment;
cmd = "send" + attachmenttype.name();
} else {
if(updates > 0) {
cmd = "editMessageText";
optionals += "&message_id=" + updates;
} else
cmd = "sendMessage";
if(this.text != null) {
if(this.text.trim().isEmpty()) {
throw new MissingException("Text");
}
text = "&text=" + this.text.trim();
} else {
throw new MissingException("Text");
}
}
if(no_web_view) {
optionals += "&disable_web_page_preview=true";
}
if(silent) {
optionals += "&disable_notification=true";
}
if(allow_sending_without_reply) {
optionals += "&allow_sending_without_reply=true";
}
String q = "chat_id=" + receiver_id + text + optionals + attachment;
if(async) {
AsyncSendable tmp = new AsyncSendable(cmd, q, receiver_id, callback, excpt);
tmp.prio = asyncprio;
tmp.isSlow = attachmenttype != Attachment.none;
return tmp;
}
return new SendableMessage(cmd, q, receiver_id);
}
/**
* is only allowed, when the Message builder was contructed using a api
* @return the send TMessage when the Message Builder is used SYNC, or null when the Message Builder is used ASYNC or has encountered an error.
*/
public TMessage send() {
return api.sendMessage(build());
}
@Getter
@AllArgsConstructor
class SendableMessage {
private final String command;
private final String q;
private final long userid;
}
class AsyncSendable extends SendableMessage {
Callback<TMessage, ?> callback;
Callback<Throwable, Void> excpt = null;
boolean prio = false;
boolean isSlow = false; // is it expected that this message is slow to porcess? sendMedia
public AsyncSendable(String cmd, String q, long userid, Callback<TMessage, ?> clb, Callback<Throwable, Void> excpt) {
super(cmd, q, userid);
callback = clb;
this.excpt = excpt;
}
}
public enum Formatting {
None(""),
HTML("HTML"),
MD("Markdown");
private String apiname;
private Formatting(String s) {
apiname = s;
}
public String getname() {
return apiname;
}
}
public enum Attachment {
none,
Video,//video need to be less than 50MB and mp4!
Document,
Audio,
Voice,
Photo,
Animation;
public static Attachment getForFileExt(String extention) {
if(extention == null) return Document;
if(extention.startsWith("."))
extention = extention.substring(1);
extention = extention.toLowerCase();
if(extention.equals("mp4")) {
return Attachment.Video;
} else if(extention.equals("mp3")) {
return Attachment.Audio;
} else if(extention.equals("ogg")) {
return Attachment.Voice;
} else if(extention.equals("jpg") || extention.equals("jpeg") || extention.equals("png")) {
return Attachment.Photo;
} else if(extention.equals("gif")) {
return Attachment.Animation;
}
return Attachment.Document;
}
public static Attachment getForFileName(String name) {
return getForFileExt(name.substring(name.lastIndexOf('.')+1));
}
}
public class MissingException extends RuntimeException {
private static final long serialVersionUID = 2750912631502103642L;
public MissingException(String missing_obj) {
super("The Object " + missing_obj + " is missing or invalid.");
}
}
}