Skip to content

Commit

Permalink
Added small http request lib to fix issues with syntaxapi.net
Browse files Browse the repository at this point in the history
  • Loading branch information
Lauriichan committed Apr 27, 2021
1 parent 5c2eadd commit 24e38fc
Show file tree
Hide file tree
Showing 11 changed files with 816 additions and 24 deletions.
22 changes: 11 additions & 11 deletions src/main/java/net/sourcewriters/minecraft/vcompat/skin/Mojang.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@

import com.syntaxphoenix.syntaxapi.logging.ILogger;
import com.syntaxphoenix.syntaxapi.logging.LogTypeId;
import com.syntaxphoenix.syntaxapi.net.http.Request;
import com.syntaxphoenix.syntaxapi.net.http.RequestType;
import com.syntaxphoenix.syntaxapi.net.http.ResponseCode;
import com.syntaxphoenix.syntaxapi.net.http.StandardContentType;

import net.sourcewriters.minecraft.vcompat.reflection.PlayerProvider;
import net.sourcewriters.minecraft.vcompat.reflection.VersionControl;
import net.sourcewriters.minecraft.vcompat.reflection.entity.NmsPlayer;
import net.sourcewriters.minecraft.vcompat.utils.java.net.EasyRequest;
import net.sourcewriters.minecraft.vcompat.utils.java.net.content.EasyUrlEncodedContent;
import net.sourcewriters.minecraft.vcompat.utils.minecraft.MojangProfileServer;
import net.sourcewriters.minecraft.vcompat.utils.minecraft.Skin;
import net.sourcewriters.minecraft.vcompat.utils.minecraft.SkinModel;
Expand Down Expand Up @@ -131,7 +131,7 @@ public Skin getSkinFrom(String url, SkinModel model, int timeout) {
}

public Skin getSkinFrom(URL url, SkinModel model) {
return getSkinFrom(url, model, 15);
return getSkinFrom(url, model, 15000);
}

public Skin getSkinFrom(URL url, SkinModel model, int timeout) {
Expand All @@ -152,11 +152,11 @@ public Skin getSkinFrom(URL url, SkinModel model, int timeout) {
logger.log(LogTypeId.ERROR, "Can't connect to url!");
return null;
}
Request request = new Request(RequestType.POST);
EasyRequest request = new EasyRequest(RequestType.POST);
request.header("Authorization", "Bearer " + profile.getAuthToken());
request.parameter("url", url.toString()).parameter("model", model.toString());
int code = request.execute(String.format(URL_SKIN_UPLOAD, profile.getUniqueId()), StandardContentType.URL_ENCODED).getCode();
if (code != ResponseCode.OK && code != ResponseCode.NO_CONTENT) {
request.data("url", url.toString()).data("model", model.toString());
int code = request.run(String.format(URL_SKIN_UPLOAD, profile.getUniqueId())).getCode();
if (code != ResponseCode.NO_CONTENT) {
return null;
}
return apply(MojangProfileServer.getSkinShorten(profile.getUniqueId()));
Expand Down Expand Up @@ -185,7 +185,7 @@ public Skin getSkinFrom(String name, String url, SkinModel model, int timeout) {
}

public Skin getSkinFrom(String name, URL url, SkinModel model) {
return getSkinFrom(name, url, model, 15);
return getSkinFrom(name, url, model, 15000);
}

public Skin getSkinFrom(String name, URL url, SkinModel model, int timeout) {
Expand All @@ -206,10 +206,10 @@ public Skin getSkinFrom(String name, URL url, SkinModel model, int timeout) {
logger.log(LogTypeId.ERROR, "Can't connect to url!");
return null;
}
Request request = new Request(RequestType.POST);
EasyRequest request = new EasyRequest(RequestType.POST);
request.header("Authorization", "Bearer " + profile.getAuthToken());
request.parameter("url", url.toString()).parameter("model", model.toString());
int code = request.execute(String.format(URL_SKIN_UPLOAD, profile.getUniqueId()), StandardContentType.URL_ENCODED).getCode();
request.data("url", url.toString()).data("model", model.toString());
int code = request.run(String.format(URL_SKIN_UPLOAD, profile.getUniqueId()), EasyUrlEncodedContent.URL_ENCODED).getCode();
if (code != ResponseCode.OK && code != ResponseCode.NO_CONTENT) {
return null;
}
Expand Down
25 changes: 12 additions & 13 deletions src/main/java/net/sourcewriters/minecraft/vcompat/skin/Profile.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
import com.syntaxphoenix.syntaxapi.json.JsonObject;
import com.syntaxphoenix.syntaxapi.json.JsonValue;
import com.syntaxphoenix.syntaxapi.json.ValueType;
import com.syntaxphoenix.syntaxapi.net.http.Request;
import com.syntaxphoenix.syntaxapi.net.http.RequestType;
import com.syntaxphoenix.syntaxapi.net.http.StandardContentType;

import net.sourcewriters.minecraft.vcompat.utils.java.net.EasyRequest;

public class Profile {

private final MojangProvider provider;

private String username;
private String password;

Expand Down Expand Up @@ -68,11 +68,11 @@ public boolean validate() {

try {

Request request = new Request(RequestType.POST);
EasyRequest request = new EasyRequest(RequestType.POST);

request.parameter("accessToken", authToken).parameter("clientToken", provider.getClientIdentifier().toString());
request.data("accessToken", authToken).data("clientToken", provider.getClientIdentifier().toString());

int code = request.execute(String.format(AUTH_SERVER, "validate"), StandardContentType.JSON).getCode();
int code = request.run(String.format(AUTH_SERVER, "validate")).getCode();

return code == 204 || code == 200;
} catch (IOException ignore) {
Expand All @@ -88,11 +88,11 @@ public Profile refresh() {

try {

Request request = new Request(RequestType.POST);
EasyRequest request = new EasyRequest(RequestType.POST);

request.parameter("accessToken", authToken).parameter("clientToken", provider.getClientIdentifier().toString());
request.data("accessToken", authToken).data("clientToken", provider.getClientIdentifier().toString());

JsonValue<?> responseRaw = request.execute(String.format(AUTH_SERVER, "refresh"), StandardContentType.JSON).getResponseAsJson();
JsonValue<?> responseRaw = request.run(String.format(AUTH_SERVER, "refresh")).getDataAsJson();

if (!responseRaw.hasType(ValueType.OBJECT)) {
return this;
Expand All @@ -119,7 +119,7 @@ public Profile authenticate() {

try {

Request request = new Request(RequestType.POST);
EasyRequest request = new EasyRequest(RequestType.POST);

JsonObject object = new JsonObject();
JsonObject agent = new JsonObject();
Expand All @@ -131,10 +131,9 @@ public Profile authenticate() {
object.set("password", password);
object.set("clientToken", provider.getClientIdentifier().toString());

request.parameter(object);
request.data(object);

JsonValue<?> responseRaw = request.execute(String.format(AUTH_SERVER, "authenticate"), StandardContentType.JSON)
.getResponseAsJson();
JsonValue<?> responseRaw = request.run(String.format(AUTH_SERVER, "authenticate")).getDataAsJson();

if (!responseRaw.hasType(ValueType.OBJECT)) {
return this;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package net.sourcewriters.minecraft.vcompat.utils.java.net;

import java.util.concurrent.ConcurrentHashMap;

import net.sourcewriters.minecraft.vcompat.utils.java.net.content.EasyJsonContent;
import net.sourcewriters.minecraft.vcompat.utils.java.net.content.EasyUrlEncodedContent;

public final class EasyContentRegistry {

private static final ConcurrentHashMap<String, IEasyContent> CONTENT = new ConcurrentHashMap<>();

static {
add(EasyJsonContent.JSON);
add(EasyUrlEncodedContent.URL_ENCODED);
}

private EasyContentRegistry() {}

public static boolean add(IEasyContent content) {
String name = content.name().toLowerCase();
if (CONTENT.contains(name)) {
return false;
}
CONTENT.put(name, content);
return true;
}

public static IEasyContent get(String name) {
return CONTENT.get(name.toLowerCase());
}

public static boolean has(String name) {
return CONTENT.containsKey(name.toLowerCase());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package net.sourcewriters.minecraft.vcompat.utils.java.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.Map.Entry;

import com.syntaxphoenix.syntaxapi.json.JsonObject;
import com.syntaxphoenix.syntaxapi.json.JsonValue;
import com.syntaxphoenix.syntaxapi.json.ValueType;
import com.syntaxphoenix.syntaxapi.json.value.JsonNull;
import com.syntaxphoenix.syntaxapi.net.http.RequestType;
import com.syntaxphoenix.syntaxapi.utils.java.Streams;

import net.sourcewriters.minecraft.vcompat.utils.java.net.content.EasyJsonContent;

public class EasyRequest {

private static final String[] EMPTY = new String[0];

private final HashMap<String, ArrayList<String>> headers = new HashMap<>();
private final RequestType requestType;

private JsonValue<?> data;

private int readTimeout = 20000;
private int connectTimeout = 30000;

public EasyRequest(RequestType requestType) {
this.requestType = Objects.requireNonNull(requestType, "RequestType is needed to cast an Http request");
}

public RequestType getRequestType() {
return requestType;
}

public int getReadTimeout() {
return readTimeout;
}

public EasyRequest setReadTimeout(long readTimeout) {
return setReadTimeout(readTimeout, TimeUnit.MILLISECONDS);
}

public EasyRequest setReadTimeout(long readTimeout, TimeUnit unit) {
this.readTimeout = (readTimeout = unit.toMillis(Math.abs(readTimeout))) > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) readTimeout;
return this;
}

public int getConnectTimeout() {
return connectTimeout;
}

public EasyRequest setConnectTimeout(long connectTimeout) {
return setReadTimeout(connectTimeout, TimeUnit.MILLISECONDS);
}

public EasyRequest setConnectTimeout(long connectTimeout, TimeUnit unit) {
this.connectTimeout = (connectTimeout = unit.toMillis(Math.abs(connectTimeout))) > Integer.MAX_VALUE ? Integer.MAX_VALUE
: (int) connectTimeout;
return this;
}

public String[] header(String name) {
return headers.containsKey(name) ? headers.get(name).toArray(EMPTY) : EMPTY;
}

public EasyRequest header(String name, Object... values) {
ArrayList<String> current = headers.computeIfAbsent(name, ignore -> new ArrayList<>());
for (Object value : values) {
current.add(value.toString());
}
return this;
}

public EasyRequest clearHeader(String name) {
headers.remove(name);
return this;
}

public EasyRequest clearHeaders() {
headers.clear();
return this;
}

public boolean hasHeaders() {
return !headers.isEmpty();
}

public EasyRequest data(String field, JsonValue<?> data) {
Objects.requireNonNull(field, "Data field name cant be null");
data = data == null ? JsonNull.get() : data;
JsonValue<?> output = this.data;
if (output == null || !output.hasType(ValueType.OBJECT)) {
this.data = (output = new JsonObject());
}
((JsonObject) output).set(field, data);
return this;
}

public EasyRequest data(String field, Object data) {
return data(field, JsonValue.fromPrimitive(data));
}

public EasyRequest data(JsonValue<?> data) {
this.data = (data != null && data.hasType(ValueType.NULL)) ? null : data;
return this;
}

public EasyRequest data(Object data) {
return data(JsonValue.fromPrimitive(data));
}

public JsonValue<?> data() {
return data;
}

public boolean hasData() {
return data != null;
}

public EasyResponse run(String url) throws IOException {
return run(url, EasyJsonContent.JSON);
}

public EasyResponse run(URL url) throws IOException {
return run(url, EasyJsonContent.JSON);
}

public EasyResponse run(String url, String contentName) throws IOException {
return run(url, EasyContentRegistry.get(contentName));
}

public EasyResponse run(URL url, String contentName) throws IOException {
return run(url, EasyContentRegistry.get(contentName));
}

public EasyResponse run(String url, IEasyContent content) throws IOException {
return run(new URL(url), content);
}

public EasyResponse run(URL url, IEasyContent content) throws IOException {

boolean output = hasData() && requestType.hasOutput();
byte[] data = null;
if (output) {
if (content.modifyUrl()) {
output = false;
content.modify(url, this.data);
} else {
data = content.serialize(this.data);
}
}

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestType.name());
connection.setDoOutput(requestType.hasOutput());

connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);

for (Entry<String, ArrayList<String>> header : headers.entrySet()) {
connection.setRequestProperty(header.getKey(), String.join("; ", header.getValue()));
}
if (requestType.hasOutput()) {
connection.setRequestProperty("Content-Type", content.type());
connection.setFixedLengthStreamingMode(output ? data.length : 0);
}

connection.connect();

if (output) {
OutputStream streamOut = connection.getOutputStream();
streamOut.write(data);
streamOut.flush();
streamOut.close();
}

InputStream streamIn = null;
try {
streamIn = connection.getInputStream();
if (streamIn == null) {
streamIn = connection.getErrorStream();
}
} catch (IOException ignore) {
streamIn = connection.getErrorStream();
}

byte[] input = IEasyContent.EMPTY;
if (streamIn != null) {
input = Streams.toByteArray(streamIn);
}
int code = connection.getResponseCode();
Map<String, List<String>> headers = connection.getHeaderFields();
connection.disconnect();

return new EasyResponse(code, input, headers);
}

}
Loading

0 comments on commit 24e38fc

Please sign in to comment.