| 1 | package com.mojang.realmsclient.client;
|
| 2 |
|
| 3 | import com.google.gson.JsonElement;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import com.mojang.realmsclient.dto.UploadInfo;
|
| 6 | import com.mojang.realmsclient.gui.screens.UploadResult;
|
| 7 | import java.io.File;
|
| 8 | import java.io.FileInputStream;
|
| 9 | import java.io.IOException;
|
| 10 | import java.io.InputStream;
|
| 11 | import java.net.http.HttpClient;
|
| 12 | import java.net.http.HttpRequest;
|
| 13 | import java.net.http.HttpResponse;
|
| 14 | import java.net.http.HttpRequest.BodyPublisher;
|
| 15 | import java.net.http.HttpRequest.BodyPublishers;
|
| 16 | import java.net.http.HttpResponse.BodyHandlers;
|
| 17 | import java.nio.charset.StandardCharsets;
|
| 18 | import java.time.Duration;
|
| 19 | import java.util.concurrent.CompletableFuture;
|
| 20 | import java.util.function.Supplier;
|
| 21 | import net.fabricmc.api.EnvType;
|
| 22 | import net.fabricmc.api.Environment;
|
| 23 | import net.minecraft.client.User;
|
| 24 | import net.minecraft.util.LenientJsonParser;
|
| 25 | import net.minecraft.util.Util;
|
| 26 | import org.apache.commons.io.input.CountingInputStream;
|
| 27 | import org.jspecify.annotations.Nullable;
|
| 28 | import org.slf4j.Logger;
|
| 29 |
|
| 30 | @Environment(EnvType.CLIENT)
|
| 31 | public class FileUpload implements AutoCloseable {
|
| 32 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 33 | private static final int MAX_RETRIES = 5;
|
| 34 | private static final String UPLOAD_PATH = "/upload";
|
| 35 | private final File file;
|
| 36 | private final long realmId;
|
| 37 | private final int slotId;
|
| 38 | private final UploadInfo uploadInfo;
|
| 39 | private final String sessionId;
|
| 40 | private final String username;
|
| 41 | private final String clientVersion;
|
| 42 | private final String worldVersion;
|
| 43 | private final UploadStatus uploadStatus;
|
| 44 | private final HttpClient client;
|
| 45 |
|
| 46 | public FileUpload(
|
| 47 | final File file,
|
| 48 | final long realmId,
|
| 49 | final int slotId,
|
| 50 | final UploadInfo uploadInfo,
|
| 51 | final User user,
|
| 52 | final String clientVersion,
|
| 53 | final String worldVersion,
|
| 54 | final UploadStatus uploadStatus
|
| 55 | ) {
|
| 56 | this.file = file;
|
| 57 | this.realmId = realmId;
|
| 58 | this.slotId = slotId;
|
| 59 | this.uploadInfo = uploadInfo;
|
| 60 | this.sessionId = user.getSessionId();
|
| 61 | this.username = user.getName();
|
| 62 | this.clientVersion = clientVersion;
|
| 63 | this.worldVersion = worldVersion;
|
| 64 | this.uploadStatus = uploadStatus;
|
| 65 | this.client = HttpClient.newBuilder().executor(Util.nonCriticalIoPool()).connectTimeout(Duration.ofSeconds(15L)).build();
|
| 66 | }
|
| 67 |
|
| 68 | @Override
|
| 69 | public void close() {
|
| 70 | this.client.close();
|
| 71 | }
|
| 72 |
|
| 73 | public CompletableFuture<UploadResult> startUpload() {
|
| 74 | long fileSize = this.file.length();
|
| 75 | this.uploadStatus.setTotalBytes(fileSize);
|
| 76 | return this.requestUpload(0, fileSize);
|
| 77 | }
|
| 78 |
|
| 79 | private CompletableFuture<UploadResult> requestUpload(final int currentAttempt, final long fileSize) {
|
| 80 | BodyPublisher publisher = inputStreamPublisherWithSize(() -> {
|
| 81 | try {
|
| 82 | return new FileUpload.UploadCountingInputStream(new FileInputStream(this.file), this.uploadStatus);
|
| 83 | } catch (IOException e) {
|
| 84 | LOGGER.warn("Failed to open file {}", this.file, e);
|
| 85 | return null;
|
| 86 | }
|
| 87 | }, fileSize);
|
| 88 | HttpRequest request = HttpRequest.newBuilder(this.uploadInfo.uploadEndpoint().resolve("/upload/" + this.realmId + "/" + this.slotId))
|
| 89 | .timeout(Duration.ofMinutes(10L))
|
| 90 | .setHeader("Cookie", this.uploadCookie())
|
| 91 | .setHeader("Content-Type", "application/octet-stream")
|
| 92 | .POST(publisher)
|
| 93 | .build();
|
| 94 | return this.client.sendAsync(request, BodyHandlers.ofString(StandardCharsets.UTF_8)).thenCompose(response -> {
|
| 95 | long retryDelaySeconds = this.getRetryDelaySeconds((HttpResponse<?>)response);
|
| 96 | if (this.shouldRetry(retryDelaySeconds, currentAttempt)) {
|
| 97 | this.uploadStatus.restart();
|
| 98 |
|
| 99 | try {
|
| 100 | Thread.sleep(Duration.ofSeconds(retryDelaySeconds));
|
| 101 | } catch (InterruptedException var8) {
|
| 102 | }
|
| 103 |
|
| 104 | return this.requestUpload(currentAttempt + 1, fileSize);
|
| 105 | } else {
|
| 106 | return CompletableFuture.completedFuture(this.handleResponse((HttpResponse<String>)response));
|
| 107 | }
|
| 108 | });
|
| 109 | }
|
| 110 |
|
| 111 | private static BodyPublisher inputStreamPublisherWithSize(final Supplier<@Nullable InputStream> inputStreamSupplier, final long fileSize) {
|
| 112 | return BodyPublishers.fromPublisher(BodyPublishers.ofInputStream(inputStreamSupplier), fileSize);
|
| 113 | }
|
| 114 |
|
| 115 | private String uploadCookie() {
|
| 116 | return "sid="
|
| 117 | + this.sessionId
|
| 118 | + ";token="
|
| 119 | + this.uploadInfo.token()
|
| 120 | + ";user="
|
| 121 | + this.username
|
| 122 | + ";version="
|
| 123 | + this.clientVersion
|
| 124 | + ";worldVersion="
|
| 125 | + this.worldVersion;
|
| 126 | }
|
| 127 |
|
| 128 | private UploadResult handleResponse(final HttpResponse<String> response) {
|
| 129 | int statusCode = response.statusCode();
|
| 130 | if (statusCode == 401) {
|
| 131 | LOGGER.debug("Realms server returned 401: {}", response.headers().firstValue("WWW-Authenticate"));
|
| 132 | }
|
| 133 |
|
| 134 | String errorMessage = null;
|
| 135 | String body = response.body();
|
| 136 | if (body != null && !body.isBlank()) {
|
| 137 | try {
|
| 138 | JsonElement errorMsgElement = LenientJsonParser.parse(body).getAsJsonObject().get("errorMsg");
|
| 139 | if (errorMsgElement != null) {
|
| 140 | errorMessage = errorMsgElement.getAsString();
|
| 141 | }
|
| 142 | } catch (Exception e) {
|
| 143 | LOGGER.warn("Failed to parse response {}", body, e);
|
| 144 | }
|
| 145 | }
|
| 146 |
|
| 147 | return new UploadResult(statusCode, errorMessage);
|
| 148 | }
|
| 149 |
|
| 150 | private boolean shouldRetry(final long retryDelaySeconds, final int currentAttempt) {
|
| 151 | return retryDelaySeconds > 0L && currentAttempt + 1 < 5;
|
| 152 | }
|
| 153 |
|
| 154 | private long getRetryDelaySeconds(final HttpResponse<?> response) {
|
| 155 | return response.headers().firstValueAsLong("Retry-After").orElse(0L);
|
| 156 | }
|
| 157 |
|
| 158 | @Environment(EnvType.CLIENT)
|
| 159 | private static class UploadCountingInputStream extends CountingInputStream {
|
| 160 | private final UploadStatus uploadStatus;
|
| 161 |
|
| 162 | private UploadCountingInputStream(final InputStream proxy, final UploadStatus uploadStatus) {
|
| 163 | super(proxy);
|
| 164 | this.uploadStatus = uploadStatus;
|
| 165 | }
|
| 166 |
|
| 167 | @Override
|
| 168 | protected void afterRead(final int n) throws IOException {
|
| 169 | super.afterRead(n);
|
| 170 | this.uploadStatus.onWrite(this.getByteCount());
|
| 171 | }
|
| 172 | }
|
| 173 | }
|
| 174 |
|