FileDownload .java

com.mojang.realmsclient.client.FileDownload (class, 411 lines): members: DownloadCountingOutputStream, findAvailableFolderName, INVALID_FILE_NAMES, error.

com.mojang.realmsclient.clientclass411 linesclient12.6 KB

API Surface (8)

OptionalLong contentLength(final String downloadLink)
void download(final WorldDownload worldDownload, final String worldName, final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus, final LevelStorageSource levelStorageSource)
void cancel()
boolean isFinished()
boolean isError()
boolean isExtracting()
String findAvailableFolderName(String folder)
void afterWrite(final int n)

Fields & Constants (14)

LOGGER
INVALID_FILE_NAMES
cancelled
finished
error
extracting
tempFile
resourcePackPath
pendingRequest
currentThread
worldDownload
worldName
downloadStatus
levelStorageSource

String literals (34)

"CLOCK$"
"COM1"
"COM2"
"COM3"
"COM4"
"COM5"
"COM6"
"COM7"
"COM8"
"COM9"
"LPT1"
"LPT2"
"LPT3"
"LPT4"
"LPT5"
"LPT6"
"LPT7"
"LPT8"
"LPT9"
"Content-Length"
"Unable to get content length for download"
"backup"
".tar.gz"
"Caught exception while downloading world"

Full Source

FileDownload.java411 lines · Minecraft 26.3 · verbatim
1
package com.mojang.realmsclient.client;
2
3
import com.google.common.hash.Hashing;
4
import com.google.common.io.Files;
5
import com.mojang.logging.LogUtils;
6
import com.mojang.realmsclient.dto.WorldDownload;
7
import com.mojang.realmsclient.exception.RealmsDefaultUncaughtExceptionHandler;
8
import com.mojang.realmsclient.gui.screens.RealmsDownloadLatestWorldScreen;
9
import java.io.BufferedInputStream;
10
import java.io.File;
11
import java.io.FileInputStream;
12
import java.io.FileOutputStream;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.OutputStream;
16
import java.net.URI;
17
import java.net.http.HttpClient;
18
import java.net.http.HttpRequest;
19
import java.net.http.HttpResponse;
20
import java.net.http.HttpRequest.Builder;
21
import java.net.http.HttpResponse.BodyHandlers;
22
import java.nio.file.Path;
23
import java.time.Duration;
24
import java.util.Locale;
25
import java.util.OptionalLong;
26
import java.util.concurrent.CancellationException;
27
import java.util.concurrent.CompletableFuture;
28
import java.util.concurrent.CompletionException;
29
import java.util.regex.Matcher;
30
import java.util.regex.Pattern;
31
import javax.annotation.CheckReturnValue;
32
import net.fabricmc.api.EnvType;
33
import net.fabricmc.api.Environment;
34
import net.minecraft.SharedConstants;
35
import net.minecraft.client.Minecraft;
36
import net.minecraft.nbt.NbtException;
37
import net.minecraft.nbt.ReportedNbtException;
38
import net.minecraft.util.FileUtil;
39
import net.minecraft.util.Util;
40
import net.minecraft.world.level.storage.LevelResource;
41
import net.minecraft.world.level.storage.LevelStorageSource;
42
import net.minecraft.world.level.storage.LevelStorageSource.LevelDirectory;
43
import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess;
44
import net.minecraft.world.level.validation.ContentValidationException;
45
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
46
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
47
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
48
import org.apache.commons.io.FileUtils;
49
import org.apache.commons.io.IOUtils;
50
import org.apache.commons.io.output.CountingOutputStream;
51
import org.apache.commons.lang3.StringUtils;
52
import org.jspecify.annotations.Nullable;
53
import org.slf4j.Logger;
54
55
@Environment(EnvType.CLIENT)
56
public class FileDownload {
57
	private static final Logger LOGGER = LogUtils.getLogger();
58
	private volatile boolean cancelled;
59
	private volatile boolean finished;
60
	private volatile boolean error;
61
	private volatile boolean extracting;
62
	private volatile @Nullable File tempFile;
63
	private volatile File resourcePackPath;
64
	private volatile @Nullable CompletableFuture<?> pendingRequest;
65
	private @Nullable Thread currentThread;
66
	private static final String[] INVALID_FILE_NAMES = new String[]{
67
		"CON",
68
		"COM",
69
		"PRN",
70
		"AUX",
71
		"CLOCK$",
72
		"NUL",
73
		"COM1",
74
		"COM2",
75
		"COM3",
76
		"COM4",
77
		"COM5",
78
		"COM6",
79
		"COM7",
80
		"COM8",
81
		"COM9",
82
		"LPT1",
83
		"LPT2",
84
		"LPT3",
85
		"LPT4",
86
		"LPT5",
87
		"LPT6",
88
		"LPT7",
89
		"LPT8",
90
		"LPT9"
91
	};
92
93
	private <T> @Nullable T joinCancellableRequest(final CompletableFuture<T> pendingRequest) throws Throwable {
94
		this.pendingRequest = pendingRequest;
95
		if (this.cancelled) {
96
			pendingRequest.cancel(true);
97
			return null;
98
		}
99
100
		try {
101
			try {
102
				return pendingRequest.join();
103
			} catch (CompletionException e) {
104
				throw e.getCause();
105
			}
106
		} catch (CancellationException e) {
107
			return null;
108
		}
109
	}
110
111
	private static HttpClient createClient() {
112
		return HttpClient.newBuilder().executor(Util.nonCriticalIoPool()).connectTimeout(Duration.ofMinutes(2L)).build();
113
	}
114
115
	private static Builder createRequest(final String downloadLink) {
116
		return HttpRequest.newBuilder(URI.create(downloadLink)).timeout(Duration.ofMinutes(2L));
117
	}
118
119
	@CheckReturnValue
120
	public static OptionalLong contentLength(final String downloadLink) {
121
		try (HttpClient client = createClient()) {
122
			HttpResponse<Void> response = client.send(createRequest(downloadLink).HEAD().build(), BodyHandlers.discarding());
123
			return response.headers().firstValueAsLong("Content-Length");
124
		} catch (Exception e) {
125
			LOGGER.error("Unable to get content length for download");
126
			return OptionalLong.empty();
127
		}
128
	}
129
130
	public void download(
131
		final WorldDownload worldDownload,
132
		final String worldName,
133
		final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus,
134
		final LevelStorageSource levelStorageSource
135
	) {
136
		if (this.currentThread == null) {
137
			this.currentThread = new Thread(() -> {
138
				try (HttpClient client = createClient()) {
139
					try {
140
						this.tempFile = File.createTempFile("backup", ".tar.gz");
141
						this.download(downloadStatus, client, worldDownload.downloadLink(), this.tempFile);
142
						this.finishWorldDownload(worldName.trim(), this.tempFile, levelStorageSource, downloadStatus);
143
					} catch (Exception e) {
144
						LOGGER.error("Caught exception while downloading world", e);
145
						this.error = true;
146
					} finally {
147
						this.pendingRequest = null;
148
						if (this.tempFile != null) {
149
							this.tempFile.delete();
150
						}
151
152
						this.tempFile = null;
153
					}
154
155
					if (this.error) {
156
						return;
157
					}
158
159
					String resourcePackLink = worldDownload.resourcePackUrl();
160
					if (!resourcePackLink.isEmpty() && !worldDownload.resourcePackHash().isEmpty()) {
161
						try {
162
							this.tempFile = File.createTempFile("resources", ".tar.gz");
163
							this.download(downloadStatus, client, resourcePackLink, this.tempFile);
164
							this.finishResourcePackDownload(downloadStatus, this.tempFile, worldDownload);
165
						} catch (Exception e) {
166
							LOGGER.error("Caught exception while downloading resource pack", e);
167
							this.error = true;
168
						} finally {
169
							this.pendingRequest = null;
170
							if (this.tempFile != null) {
171
								this.tempFile.delete();
172
							}
173
174
							this.tempFile = null;
175
						}
176
					}
177
178
					this.finished = true;
179
				}
180
			}, "Realms world download");
181
			this.currentThread.setUncaughtExceptionHandler(new RealmsDefaultUncaughtExceptionHandler(LOGGER));
182
			this.currentThread.start();
183
		}
184
	}
185
186
	private void download(final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus, final HttpClient client, final String url, final File target) throws IOException {
187
		HttpRequest request = createRequest(url).GET().build();
188
189
		HttpResponse<InputStream> response;
190
		try {
191
			response = this.joinCancellableRequest(client.sendAsync(request, BodyHandlers.ofInputStream()));
192
		} catch (Error e) {
193
			throw e;
194
		} catch (Throwable e) {
195
			LOGGER.error("Failed to download {}", url, e);
196
			this.error = true;
197
			return;
198
		}
199
200
		if (response != null && !this.cancelled) {
201
			if (response.statusCode() != 200) {
202
				this.error = true;
203
			} else {
204
				downloadStatus.totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(0L);
205
206
				try (
207
					InputStream is = response.body();
208
					OutputStream os = new FileOutputStream(target);
209
				) {
210
					is.transferTo(new FileDownload.DownloadCountingOutputStream(os, downloadStatus));
211
				}
212
			}
213
		}
214
	}
215
216
	public void cancel() {
217
		if (this.tempFile != null) {
218
			this.tempFile.delete();
219
			this.tempFile = null;
220
		}
221
222
		this.cancelled = true;
223
		CompletableFuture<?> pendingRequest = this.pendingRequest;
224
		if (pendingRequest != null) {
225
			pendingRequest.cancel(true);
226
		}
227
	}
228
229
	public boolean isFinished() {
230
		return this.finished;
231
	}
232
233
	public boolean isError() {
234
		return this.error;
235
	}
236
237
	public boolean isExtracting() {
238
		return this.extracting;
239
	}
240
241
	public static String findAvailableFolderName(String folder) {
242
		folder = folder.replaceAll("[\\./\"]", "_");
243
244
		for (String invalidName : INVALID_FILE_NAMES) {
245
			if (folder.equalsIgnoreCase(invalidName)) {
246
				folder = "_" + folder + "_";
247
			}
248
		}
249
250
		return folder;
251
	}
252
253
	private void untarGzipArchive(String name, final @Nullable File file, final LevelStorageSource levelStorageSource) throws IOException {
254
		Pattern namePattern = Pattern.compile(".*-([0-9]+)$");
255
		int number = 1;
256
257
		for (char replacer : SharedConstants.ILLEGAL_FILE_CHARACTERS) {
258
			name = name.replace(replacer, '_');
259
		}
260
261
		if (StringUtils.isEmpty(name)) {
262
			name = "Realm";
263
		}
264
265
		name = findAvailableFolderName(name);
266
267
		try {
268
			for (LevelDirectory level : levelStorageSource.findLevelCandidates()) {
269
				String levelId = level.directoryName();
270
				if (levelId.toLowerCase(Locale.ROOT).startsWith(name.toLowerCase(Locale.ROOT))) {
271
					Matcher matcher = namePattern.matcher(levelId);
272
					if (matcher.matches()) {
273
						int parsedNumber = Integer.parseInt(matcher.group(1));
274
						if (parsedNumber > number) {
275
							number = parsedNumber;
276
						}
277
					} else {
278
						number++;
279
					}
280
				}
281
			}
282
		} catch (Exception e) {
283
			LOGGER.error("Error getting level list", e);
284
			this.error = true;
285
			return;
286
		}
287
288
		String finalName;
289
		if (levelStorageSource.isNewLevelIdAcceptable(name) && number <= 1) {
290
			finalName = name;
291
		} else {
292
			finalName = name + (number == 1 ? "" : "-" + number);
293
			if (!levelStorageSource.isNewLevelIdAcceptable(finalName)) {
294
				boolean foundName = false;
295
296
				while (!foundName) {
297
					number++;
298
					finalName = name + (number == 1 ? "" : "-" + number);
299
					if (levelStorageSource.isNewLevelIdAcceptable(finalName)) {
300
						foundName = true;
301
					}
302
				}
303
			}
304
		}
305
306
		TarArchiveInputStream tarIn = null;
307
		Path worldPath = Minecraft.getInstance().getLevelSource().getLevelPath(finalName).normalize();
308
309
		try {
310
			FileUtil.createDirectoriesSafe(worldPath);
311
			tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(file))));
312
			TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
313
314
			while (tarEntry != null) {
315
				Path destPath = worldPath.resolve(Path.of("world").relativize(Path.of(tarEntry.getName()))).normalize();
316
				if (!destPath.startsWith(worldPath)) {
317
					LOGGER.warn("Unexpected entry in Realms world download: {}", tarEntry.getName());
318
					tarEntry = tarIn.getNextTarEntry();
319
				} else {
320
					if (tarEntry.isDirectory()) {
321
						FileUtil.createDirectoriesSafe(destPath);
322
					} else {
323
						Path parent = destPath.getParent();
324
						if (parent != null) {
325
							FileUtil.createDirectoriesSafe(parent);
326
						}
327
328
						try (FileOutputStream output = new FileOutputStream(destPath.toFile())) {
329
							IOUtils.copy(tarIn, output);
330
						}
331
					}
332
333
					tarEntry = tarIn.getNextTarEntry();
334
				}
335
			}
336
		} catch (Exception e) {
337
			LOGGER.error("Error extracting world", e);
338
			this.error = true;
339
		} finally {
340
			if (tarIn != null) {
341
				tarIn.close();
342
			}
343
344
			if (file != null) {
345
				file.delete();
346
			}
347
348
			try (LevelStorageAccess access = levelStorageSource.validateAndCreateAccess(finalName)) {
349
				access.renameAndDropPlayer(finalName);
350
			} catch (IOException | NbtException | ReportedNbtException e) {
351
				LOGGER.error("Failed to modify unpacked realms level {}", finalName, e);
352
			} catch (ContentValidationException e) {
353
				LOGGER.warn("Failed to download file", e);
354
			}
355
356
			this.resourcePackPath = worldPath.resolve(LevelResource.MAP_RESOURCE_FILE.id()).toFile();
357
		}
358
	}
359
360
	private void finishWorldDownload(
361
		final String worldName, final File tempFile, final LevelStorageSource levelStorageSource, final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus
362
	) {
363
		if (downloadStatus.bytesWritten >= downloadStatus.totalBytes && !this.cancelled && !this.error) {
364
			try {
365
				this.extracting = true;
366
				this.untarGzipArchive(worldName, tempFile, levelStorageSource);
367
			} catch (IOException e) {
368
				LOGGER.error("Error extracting archive", e);
369
				this.error = true;
370
			}
371
		}
372
	}
373
374
	private void finishResourcePackDownload(
375
		final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus, final File tempFile, final WorldDownload worldDownload
376
	) {
377
		if (downloadStatus.bytesWritten >= downloadStatus.totalBytes && !this.cancelled) {
378
			try {
379
				String actualHash = Hashing.sha1().hashBytes(Files.toByteArray(tempFile)).toString();
380
				if (actualHash.equals(worldDownload.resourcePackHash())) {
381
					FileUtils.copyFile(tempFile, this.resourcePackPath);
382
					this.finished = true;
383
				} else {
384
					LOGGER.error("Resourcepack had wrong hash (expected {}, found {}). Deleting it.", worldDownload.resourcePackHash(), actualHash);
385
					FileUtils.deleteQuietly(tempFile);
386
					this.error = true;
387
				}
388
			} catch (IOException e) {
389
				LOGGER.error("Error copying resourcepack file", e);
390
				this.error = true;
391
			}
392
		}
393
	}
394
395
	@Environment(EnvType.CLIENT)
396
	private static class DownloadCountingOutputStream extends CountingOutputStream {
397
		private final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus;
398
399
		public DownloadCountingOutputStream(final OutputStream out, final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus) {
400
			super(out);
401
			this.downloadStatus = downloadStatus;
402
		}
403
404
		@Override
405
		protected void afterWrite(final int n) throws IOException {
406
			super.afterWrite(n);
407
			this.downloadStatus.bytesWritten = this.getByteCount();
408
		}
409
	}
410
}
411

Decompiled Minecraft 26.3 source of FileDownload (com/mojang/realmsclient/client/FileDownload.java) with Mojang official mappings, stored verbatim on the site.