Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions jtelegrambotapi-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@
<artifactId>lombok</artifactId>
</dependency>

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>

<!-- test dependencies -->

<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import okhttp3.Request;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

@Getter
@EqualsAndHashCode(of = {"apiKey", "botInfo"})
Expand Down Expand Up @@ -45,13 +46,17 @@ public InputStream downloadFile(TelegramFile file) throws IOException {
}

public InputStream downloadFile(String filePath) throws IOException {
ResponseBody body = registry.getClient().newCall(
new Request.Builder()
.url(registry.getFileApiUrl() + apiKey + "/" + filePath)
.get()
.build()
).execute().body();

return body == null ? null : body.byteStream();
URI uri = URI.create(registry.getFileApiUrl() + apiKey + "/" + filePath);
HttpResponse<InputStream> body;
try {
body = registry.getClient().send(
HttpRequest.newBuilder()
.uri(uri)
.GET().build(), HttpResponse.BodyHandlers.ofInputStream());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}

return body == null ? null : body.body();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
import com.jtelegram.api.requests.GetMe;
import lombok.Builder;
import lombok.Getter;
import okhttp3.OkHttpClient;

import java.lang.reflect.Modifier;
import java.net.http.HttpClient;
import java.util.HashSet;
import java.util.Set;
import java.util.function.BiConsumer;
Expand Down Expand Up @@ -55,15 +55,15 @@ public class TelegramBotRegistry {
private final UpdateProvider updateProvider;
private String apiUrl = "https://api.telegram.org/bot";
private String fileApiUrl = "https://api.telegram.org/file/bot";
private OkHttpClient client = new OkHttpClient();
private HttpClient client = HttpClient.newHttpClient();
// <1 is a dynamic thread pool
// 1 is a single thread pool
// >1 is a multi thread pool
private int eventThreadCount = 1;
private final Set<TelegramBot> bots = new HashSet<>();

@Builder
private TelegramBotRegistry(UpdateProvider updateProvider, String apiUrl, OkHttpClient client, Integer eventThreadCount) {
private TelegramBotRegistry(UpdateProvider updateProvider, String apiUrl, HttpClient client, Integer eventThreadCount) {
this.updateProvider = updateProvider;

if (apiUrl != null) {
Expand All @@ -79,7 +79,7 @@ private TelegramBotRegistry(UpdateProvider updateProvider, String apiUrl, OkHttp
}
}

public void setHttpClient(OkHttpClient client) {
public void setHttpClient(HttpClient client) {
this.client = client;
bots.forEach((bot) -> bot.getRequestQueue().setClient(client));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import okhttp3.MultipartBody;
import com.jtelegram.api.util.MultipartBodyPublisher;

import java.lang.reflect.Type;

Expand All @@ -23,7 +23,7 @@ default boolean isAttachable() {
return getIdentifier() != null;
}

default void attachTo(MultipartBody.Builder builder) {}
default void attachTo(MultipartBodyPublisher.Builder builder) {}

class Serializer implements JsonSerializer<InputFile> {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,27 @@
import com.google.gson.JsonObject;
import com.jtelegram.api.TelegramBot;
import com.jtelegram.api.TelegramBotRegistry;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import com.jtelegram.api.util.MultipartBodyPublisher;

import java.io.File;
import java.net.http.HttpRequest;
import java.util.List;

public interface InputFileRequest {
MediaType OCTET_STREAM_TYPE = MediaType.parse("application/octet-stream");
String OCTET_STREAM_TYPE = "application/octet-stream";

List<InputFile> getInputFiles();

Request.Builder superBuild(TelegramBot bot);
HttpRequest.Builder superBuild(TelegramBot bot);

default Request.Builder getBuilder(TelegramBot bot) {
default HttpRequest.Builder getBuilder(TelegramBot bot) {
List<InputFile> inputFiles = getInputFiles();

if (inputFiles.stream().noneMatch(InputFile::isAttachable)) {
return superBuild(bot);
}

JsonObject obj = TelegramBotRegistry.GSON.toJsonTree(this).getAsJsonObject();
MultipartBody.Builder bodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
MultipartBodyPublisher.Builder bodyBuilder = new MultipartBodyPublisher.Builder();

obj.keySet().forEach((key) -> {
JsonElement e = obj.get(key);
Expand All @@ -40,10 +36,10 @@ default Request.Builder getBuilder(TelegramBot bot) {
val = e.toString();
}

bodyBuilder.addFormDataPart(key, val);
bodyBuilder.addPart(MultipartBodyPublisher.Part.forFormData(key, val));
});

inputFiles.stream().filter(InputFile::isAttachable).forEach((inputFile) -> inputFile.attachTo(bodyBuilder));
return superBuild(bot).post(bodyBuilder.build());
return superBuild(bot).header("Content-Type", "multipart/form-data").POST(bodyBuilder.build());
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.jtelegram.api.message.input.file;

import com.jtelegram.api.util.MultipartBodyPublisher;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.http.HttpRequest;

import lombok.ToString;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

@Getter
@ToString
Expand All @@ -20,8 +22,15 @@ public String getIdentifier() {
}

@Override
public void attachTo(MultipartBody.Builder builder) {
public void attachTo(MultipartBodyPublisher.Builder builder) {
HttpRequest.BodyPublisher filePublisher;
try {
filePublisher = HttpRequest.BodyPublishers.ofFile(data.toPath());
} catch (FileNotFoundException ex) {
throw new IllegalArgumentException("Local file not found", ex);
}
String identifier = getIdentifier();
builder.addFormDataPart(identifier, identifier, RequestBody.create(InputFileRequest.OCTET_STREAM_TYPE, data));
builder.addPart(
MultipartBodyPublisher.Part.forBodyPublisher(identifier, identifier, InputFileRequest.OCTET_STREAM_TYPE, filePublisher));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,21 @@
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import okhttp3.Response;

import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.function.Consumer;

@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class AbstractTelegramRequest implements TelegramRequest {
public abstract class AbstractTelegramRequest<T> implements TelegramRequest<T> {
// utility field
protected transient static Gson gson = TelegramBotRegistry.GSON;
private transient final String endPoint;
protected transient final Consumer<TelegramException> errorHandler;

protected String getBody(Response response) throws IOException {
return response == null ? null : response.body().string();
protected T getBody(HttpResponse<T> response) throws IOException {
return response == null ? null : response.body();
}

protected JsonElement validate(String response) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

import lombok.Getter;
import lombok.Setter;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Queue;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

Expand All @@ -21,9 +21,9 @@ public class BotRequestQueue extends Thread {
// 0 for instantaneous, negative numbers
// will result in an error
private long interval = 100;
private OkHttpClient client;
private HttpClient client;

public BotRequestQueue(OkHttpClient client) {
public BotRequestQueue(HttpClient client) {
super("Bot Request Queue");
this.client = client;
}
Expand All @@ -44,12 +44,18 @@ public void run() {
}

try {
Request httpRequest = request.getRequest().build(request.getBot()).build();
Response response = client.newCall(httpRequest).execute();

HttpRequest httpRequest = request.getRequest().build(request.getBot()).build();
HttpResponse<String> response = client.send(httpRequest,
HttpResponse.BodyHandlers.ofString(
StandardCharsets.UTF_8));

request.getRequest().handleResponse(response);
} catch (IOException ex) {
request.getRequest().handleException(ex);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@
import com.google.gson.JsonElement;
import com.jtelegram.api.ex.TelegramException;
import lombok.EqualsAndHashCode;
import okhttp3.Response;

import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.function.Consumer;

/**
* A generic telegram request class which
* has a response beyond "OK"
*/
@EqualsAndHashCode(callSuper = true)
public abstract class QueryTelegramRequest<T> extends AbstractTelegramRequest {
public abstract class QueryTelegramRequest<T> extends AbstractTelegramRequest<String> {
private transient final Consumer<T> callback;
private transient final Class<T> callbackType;

Expand All @@ -24,8 +24,9 @@ protected QueryTelegramRequest(String endPoint, Class<T> callbackType, Consumer<
}

@Override
public void handleResponse(Response response) throws IOException {
public void handleResponse(HttpResponse<String> response) throws IOException {
String body = getBody(response);
response.body();
JsonElement result;

if (body != null && (result = validate(body)) != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
package com.jtelegram.api.requests.framework;

import com.google.gson.JsonElement;
import com.jtelegram.api.TelegramBot;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public interface TelegramRequest {
MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

public interface TelegramRequest<T> {
/**
* Use GSON to properly serialize the request
* to send to Telegram's servers. This method
Expand All @@ -21,10 +20,12 @@ public interface TelegramRequest {
*/
String serialize();

default Request.Builder build(TelegramBot bot) {
return new Request.Builder()
.url(bot.getRegistry().getApiUrl() + bot.getApiKey() + "/" + getEndPoint())
.post(RequestBody.create(JSON_MEDIA_TYPE, serialize()));
default HttpRequest.Builder build(TelegramBot bot) {

return HttpRequest.newBuilder()
.uri(URI.create(bot.getRegistry().getApiUrl() + bot.getApiKey() + "/" + getEndPoint()))
.header("Content-Type", "application/json; charset=utf-8")
.POST(HttpRequest.BodyPublishers.ofString(serialize(), StandardCharsets.UTF_8));
}

/**
Expand All @@ -42,7 +43,7 @@ default Request.Builder build(TelegramBot bot) {
*
* @throws IOException If any I/O error occurred
*/
void handleResponse(Response response) throws IOException;
void handleResponse(HttpResponse<String> response) throws IOException;

/**
* Handle an exception in the case that an I/O error occured
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.jtelegram.api.requests.framework;

import com.jtelegram.api.ex.TelegramException;
import okhttp3.Response;

import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.function.Consumer;

/**
Expand All @@ -13,7 +13,7 @@
* the request was successful or there was an error.
*
*/
public abstract class UpdateTelegramRequest extends AbstractTelegramRequest {
public abstract class UpdateTelegramRequest extends AbstractTelegramRequest<String> {
protected transient Runnable callback;

protected UpdateTelegramRequest(String endPoint, Consumer<TelegramException> errorHandler, Runnable callback) {
Expand All @@ -22,7 +22,7 @@ protected UpdateTelegramRequest(String endPoint, Consumer<TelegramException> err
}

@Override
public void handleResponse(Response response) throws IOException {
public void handleResponse(HttpResponse<String> response) throws IOException {
String body = getBody(response);

if (body != null && validate(body) != null) {
Expand Down
Loading