| 1 | package net.minecraft.client.resources.server;
|
| 2 |
|
| 3 | import com.google.common.collect.Lists;
|
| 4 | import com.google.common.hash.HashCode;
|
| 5 | import com.google.common.hash.HashFunction;
|
| 6 | import com.google.common.hash.Hashing;
|
| 7 | import com.mojang.logging.LogUtils;
|
| 8 | import com.mojang.realmsclient.Unit;
|
| 9 | import com.mojang.util.UndashedUuid;
|
| 10 | import java.io.IOException;
|
| 11 | import java.io.UncheckedIOException;
|
| 12 | import java.net.Proxy;
|
| 13 | import java.net.URL;
|
| 14 | import java.nio.file.Path;
|
| 15 | import java.util.ArrayList;
|
| 16 | import java.util.List;
|
| 17 | import java.util.Locale;
|
| 18 | import java.util.Map;
|
| 19 | import java.util.Optional;
|
| 20 | import java.util.OptionalLong;
|
| 21 | import java.util.UUID;
|
| 22 | import java.util.concurrent.CompletableFuture;
|
| 23 | import java.util.concurrent.Executor;
|
| 24 | import java.util.function.Consumer;
|
| 25 | import java.util.regex.Pattern;
|
| 26 | import net.fabricmc.api.EnvType;
|
| 27 | import net.fabricmc.api.Environment;
|
| 28 | import net.minecraft.SharedConstants;
|
| 29 | import net.minecraft.WorldVersion;
|
| 30 | import net.minecraft.client.Minecraft;
|
| 31 | import net.minecraft.client.User;
|
| 32 | import net.minecraft.client.gui.components.toasts.SystemToast;
|
| 33 | import net.minecraft.client.main.GameConfig;
|
| 34 | import net.minecraft.network.Connection;
|
| 35 | import net.minecraft.network.chat.Component;
|
| 36 | import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
| 37 | import net.minecraft.network.protocol.common.ServerboundResourcePackPacket.Action;
|
| 38 | import net.minecraft.server.packs.DownloadQueue;
|
| 39 | import net.minecraft.server.packs.PackLocationInfo;
|
| 40 | import net.minecraft.server.packs.PackSelectionConfig;
|
| 41 | import net.minecraft.server.packs.PackType;
|
| 42 | import net.minecraft.server.packs.DownloadQueue.BatchConfig;
|
| 43 | import net.minecraft.server.packs.DownloadQueue.BatchResult;
|
| 44 | import net.minecraft.server.packs.DownloadQueue.DownloadRequest;
|
| 45 | import net.minecraft.server.packs.FilePackResources.FileResourcesSupplier;
|
| 46 | import net.minecraft.server.packs.metadata.pack.PackFormat;
|
| 47 | import net.minecraft.server.packs.repository.Pack;
|
| 48 | import net.minecraft.server.packs.repository.PackSource;
|
| 49 | import net.minecraft.server.packs.repository.RepositorySource;
|
| 50 | import net.minecraft.server.packs.repository.Pack.Metadata;
|
| 51 | import net.minecraft.server.packs.repository.Pack.Position;
|
| 52 | import net.minecraft.server.packs.repository.Pack.ResourcesSupplier;
|
| 53 | import net.minecraft.util.HttpUtil.DownloadProgressListener;
|
| 54 | import org.jspecify.annotations.Nullable;
|
| 55 | import org.slf4j.Logger;
|
| 56 |
|
| 57 | @Environment(EnvType.CLIENT)
|
| 58 | public class DownloadedPackSource implements AutoCloseable {
|
| 59 | private static final Component SERVER_NAME = Component.translatable("resourcePack.server.name");
|
| 60 | private static final Pattern SHA1 = Pattern.compile("^[a-fA-F0-9]{40}$");
|
| 61 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 62 | private static final RepositorySource EMPTY_SOURCE = result -> {};
|
| 63 | private static final PackSelectionConfig DOWNLOADED_PACK_SELECTION = new PackSelectionConfig(true, Position.TOP, true);
|
| 64 | private static final PackLoadFeedback LOG_ONLY_FEEDBACK = new PackLoadFeedback() {
|
| 65 | @Override
|
| 66 | public void reportUpdate(final UUID id, final PackLoadFeedback.Update update) {
|
| 67 | DownloadedPackSource.LOGGER.debug("Downloaded pack {} changed state to {}", id, update);
|
| 68 | }
|
| 69 |
|
| 70 | @Override
|
| 71 | public void reportFinalResult(final UUID id, final PackLoadFeedback.FinalResult result) {
|
| 72 | DownloadedPackSource.LOGGER.debug("Downloaded pack {} finished with state {}", id, result);
|
| 73 | }
|
| 74 | };
|
| 75 | private final Minecraft minecraft;
|
| 76 | private RepositorySource packSource = EMPTY_SOURCE;
|
| 77 | private PackReloadConfig.@Nullable Callbacks pendingReload;
|
| 78 | private final ServerPackManager manager;
|
| 79 | private final DownloadQueue downloadQueue;
|
| 80 | private PackSource packType = PackSource.SERVER;
|
| 81 | private PackLoadFeedback packFeedback = LOG_ONLY_FEEDBACK;
|
| 82 | private int packIdSerialNumber;
|
| 83 |
|
| 84 | public DownloadedPackSource(final Minecraft minecraft, final Path packCache, final GameConfig.UserData user) {
|
| 85 | this.minecraft = minecraft;
|
| 86 |
|
| 87 | try {
|
| 88 | this.downloadQueue = new DownloadQueue(packCache);
|
| 89 | } catch (IOException e) {
|
| 90 | throw new UncheckedIOException("Failed to open download queue in directory " + packCache, e);
|
| 91 | }
|
| 92 |
|
| 93 | Executor executor = minecraft::schedule;
|
| 94 | this.manager = new ServerPackManager(this.createDownloader(this.downloadQueue, executor, user.user, user.proxy), new PackLoadFeedback() {
|
| 95 | @Override
|
| 96 | public void reportUpdate(final UUID id, final PackLoadFeedback.Update result) {
|
| 97 | DownloadedPackSource.this.packFeedback.reportUpdate(id, result);
|
| 98 | }
|
| 99 |
|
| 100 | @Override
|
| 101 | public void reportFinalResult(final UUID id, final PackLoadFeedback.FinalResult result) {
|
| 102 | DownloadedPackSource.this.packFeedback.reportFinalResult(id, result);
|
| 103 | }
|
| 104 | }, this.createReloadConfig(), this.createUpdateScheduler(executor), ServerPackManager.PackPromptStatus.PENDING);
|
| 105 | }
|
| 106 |
|
| 107 | private DownloadProgressListener createDownloadNotifier(final int totalCount) {
|
| 108 | return new DownloadProgressListener() {
|
| 109 | private final SystemToast.SystemToastId toastId = new SystemToast.SystemToastId();
|
| 110 | private Component title = Component.empty();
|
| 111 | private @Nullable Component message = null;
|
| 112 | private int count;
|
| 113 | private int failCount;
|
| 114 | private OptionalLong totalBytes = OptionalLong.empty();
|
| 115 |
|
| 116 | private void updateToast() {
|
| 117 | DownloadedPackSource.this.minecraft
|
| 118 | .execute(() -> SystemToast.addOrUpdate(DownloadedPackSource.this.minecraft.gui.toastManager(), this.toastId, this.title, this.message));
|
| 119 | }
|
| 120 |
|
| 121 | private void updateProgress(final long bytesSoFar) {
|
| 122 | if (this.totalBytes.isPresent()) {
|
| 123 | this.message = Component.translatable("download.pack.progress.percent", bytesSoFar * 100L / this.totalBytes.getAsLong());
|
| 124 | } else {
|
| 125 | this.message = Component.translatable("download.pack.progress.bytes", Unit.humanReadable(bytesSoFar));
|
| 126 | }
|
| 127 |
|
| 128 | this.updateToast();
|
| 129 | }
|
| 130 |
|
| 131 | @Override
|
| 132 | public void requestStart() {
|
| 133 | this.count++;
|
| 134 | this.title = Component.translatable("download.pack.title", this.count, totalCount);
|
| 135 | this.updateToast();
|
| 136 | DownloadedPackSource.LOGGER.debug("Starting pack {}/{} download", this.count, totalCount);
|
| 137 | }
|
| 138 |
|
| 139 | @Override
|
| 140 | public void downloadStart(final OptionalLong sizeBytes) {
|
| 141 | DownloadedPackSource.LOGGER.debug("File size = {} bytes", sizeBytes);
|
| 142 | this.totalBytes = sizeBytes;
|
| 143 | this.updateProgress(0L);
|
| 144 | }
|
| 145 |
|
| 146 | @Override
|
| 147 | public void downloadedBytes(final long bytesSoFar) {
|
| 148 | DownloadedPackSource.LOGGER.debug("Progress for pack {}: {} bytes", this.count, bytesSoFar);
|
| 149 | this.updateProgress(bytesSoFar);
|
| 150 | }
|
| 151 |
|
| 152 | @Override
|
| 153 | public void requestFinished(final boolean success) {
|
| 154 | if (!success) {
|
| 155 | DownloadedPackSource.LOGGER.info("Pack {} failed to download", this.count);
|
| 156 | this.failCount++;
|
| 157 | } else {
|
| 158 | DownloadedPackSource.LOGGER.debug("Download ended for pack {}", this.count);
|
| 159 | }
|
| 160 |
|
| 161 | if (this.count == totalCount) {
|
| 162 | if (this.failCount > 0) {
|
| 163 | this.title = Component.translatable("download.pack.failed", this.failCount, totalCount);
|
| 164 | this.message = null;
|
| 165 | this.updateToast();
|
| 166 | } else {
|
| 167 | SystemToast.forceHide(DownloadedPackSource.this.minecraft.gui.toastManager(), this.toastId);
|
| 168 | }
|
| 169 | }
|
| 170 | }
|
| 171 | };
|
| 172 | }
|
| 173 |
|
| 174 | private PackDownloader createDownloader(final DownloadQueue downloadQueue, final Executor mainThreadExecutor, final User user, final Proxy proxy) {
|
| 175 | return new PackDownloader() {
|
| 176 | private static final int MAX_PACK_SIZE_BYTES = 262144000;
|
| 177 | private static final HashFunction CACHE_HASHING_FUNCTION = Hashing.sha1();
|
| 178 |
|
| 179 | private Map<String, String> createDownloadHeaders() {
|
| 180 | WorldVersion version = SharedConstants.getCurrentVersion();
|
| 181 | return Map.of(
|
| 182 | "X-Minecraft-Username",
|
| 183 | user.getName(),
|
| 184 | "X-Minecraft-UUID",
|
| 185 | UndashedUuid.toString(user.getProfileId()),
|
| 186 | "X-Minecraft-Version",
|
| 187 | version.name(),
|
| 188 | "X-Minecraft-Version-ID",
|
| 189 | version.id(),
|
| 190 | "X-Minecraft-Pack-Format",
|
| 191 | String.valueOf(version.packVersion(PackType.CLIENT_RESOURCES)),
|
| 192 | "User-Agent",
|
| 193 | "Minecraft Java/" + version.name()
|
| 194 | );
|
| 195 | }
|
| 196 |
|
| 197 | @Override
|
| 198 | public void download(final Map<UUID, DownloadRequest> requests, final Consumer<BatchResult> output) {
|
| 199 | downloadQueue.downloadBatch(
|
| 200 | new BatchConfig(CACHE_HASHING_FUNCTION, 262144000, this.createDownloadHeaders(), proxy, DownloadedPackSource.this.createDownloadNotifier(requests.size())),
|
| 201 | requests
|
| 202 | )
|
| 203 | .thenAcceptAsync(output, mainThreadExecutor);
|
| 204 | }
|
| 205 | };
|
| 206 | }
|
| 207 |
|
| 208 | private Runnable createUpdateScheduler(final Executor mainThreadExecutor) {
|
| 209 | return new Runnable() {
|
| 210 | private boolean scheduledInMainExecutor;
|
| 211 | private boolean hasUpdates;
|
| 212 |
|
| 213 | @Override
|
| 214 | public void run() {
|
| 215 | this.hasUpdates = true;
|
| 216 | if (!this.scheduledInMainExecutor) {
|
| 217 | this.scheduledInMainExecutor = true;
|
| 218 | mainThreadExecutor.execute(this::runAllUpdates);
|
| 219 | }
|
| 220 | }
|
| 221 |
|
| 222 | private void runAllUpdates() {
|
| 223 | while (this.hasUpdates) {
|
| 224 | this.hasUpdates = false;
|
| 225 | DownloadedPackSource.this.manager.tick();
|
| 226 | }
|
| 227 |
|
| 228 | this.scheduledInMainExecutor = false;
|
| 229 | }
|
| 230 | };
|
| 231 | }
|
| 232 |
|
| 233 | private PackReloadConfig createReloadConfig() {
|
| 234 | return this::startReload;
|
| 235 | }
|
| 236 |
|
| 237 | private @Nullable List<Pack> loadRequestedPacks(final List<PackReloadConfig.IdAndPath> packsToLoad) {
|
| 238 | List<Pack> packs = new ArrayList<>(packsToLoad.size());
|
| 239 |
|
| 240 | for (PackReloadConfig.IdAndPath idAndPath : Lists.reverse(packsToLoad)) {
|
| 241 | String name = String.format(Locale.ROOT, "server/%08X/%s", this.packIdSerialNumber++, idAndPath.id());
|
| 242 | Path path = idAndPath.path();
|
| 243 | PackLocationInfo packLocationInfo = new PackLocationInfo(name, SERVER_NAME, this.packType, Optional.empty());
|
| 244 | ResourcesSupplier resources = new FileResourcesSupplier(path);
|
| 245 | PackFormat currentPackVersion = SharedConstants.getCurrentVersion().packVersion(PackType.CLIENT_RESOURCES);
|
| 246 | Metadata metadata = Pack.readPackMetadata(packLocationInfo, resources, currentPackVersion, PackType.CLIENT_RESOURCES);
|
| 247 | if (metadata == null) {
|
| 248 | LOGGER.warn("Invalid pack metadata in {}, ignoring all", path);
|
| 249 | return null;
|
| 250 | }
|
| 251 |
|
| 252 | packs.add(new Pack(packLocationInfo, resources, metadata, DOWNLOADED_PACK_SELECTION));
|
| 253 | }
|
| 254 |
|
| 255 | return packs;
|
| 256 | }
|
| 257 |
|
| 258 | public RepositorySource createRepositorySource() {
|
| 259 | return output -> this.packSource.loadPacks(output);
|
| 260 | }
|
| 261 |
|
| 262 | private static RepositorySource configureSource(final List<Pack> packs) {
|
| 263 | return packs.isEmpty() ? EMPTY_SOURCE : packs::forEach;
|
| 264 | }
|
| 265 |
|
| 266 | private void startReload(final PackReloadConfig.Callbacks callbacks) {
|
| 267 | this.pendingReload = callbacks;
|
| 268 | List<PackReloadConfig.IdAndPath> normalPacks = callbacks.packsToLoad();
|
| 269 | List<Pack> packs = this.loadRequestedPacks(normalPacks);
|
| 270 | if (packs == null) {
|
| 271 | callbacks.onFailure(false);
|
| 272 | List<PackReloadConfig.IdAndPath> recoveryPacks = callbacks.packsToLoad();
|
| 273 | packs = this.loadRequestedPacks(recoveryPacks);
|
| 274 | if (packs == null) {
|
| 275 | LOGGER.warn("Double failure in loading server packs");
|
| 276 | packs = List.of();
|
| 277 | }
|
| 278 | }
|
| 279 |
|
| 280 | this.packSource = configureSource(packs);
|
| 281 | this.minecraft.reloadResourcePacks();
|
| 282 | }
|
| 283 |
|
| 284 | public void onRecovery() {
|
| 285 | if (this.pendingReload != null) {
|
| 286 | this.pendingReload.onFailure(false);
|
| 287 | List<Pack> packs = this.loadRequestedPacks(this.pendingReload.packsToLoad());
|
| 288 | if (packs == null) {
|
| 289 | LOGGER.warn("Double failure in loading server packs");
|
| 290 | packs = List.of();
|
| 291 | }
|
| 292 |
|
| 293 | this.packSource = configureSource(packs);
|
| 294 | }
|
| 295 | }
|
| 296 |
|
| 297 | public void onRecoveryFailure() {
|
| 298 | if (this.pendingReload != null) {
|
| 299 | this.pendingReload.onFailure(true);
|
| 300 | this.pendingReload = null;
|
| 301 | this.packSource = EMPTY_SOURCE;
|
| 302 | }
|
| 303 | }
|
| 304 |
|
| 305 | public void onReloadSuccess() {
|
| 306 | if (this.pendingReload != null) {
|
| 307 | this.pendingReload.onSuccess();
|
| 308 | this.pendingReload = null;
|
| 309 | }
|
| 310 | }
|
| 311 |
|
| 312 | private static @Nullable HashCode tryParseSha1Hash(final @Nullable String hash) {
|
| 313 | return hash != null && SHA1.matcher(hash).matches() ? HashCode.fromString(hash.toLowerCase(Locale.ROOT)) : null;
|
| 314 | }
|
| 315 |
|
| 316 | public void pushPack(final UUID id, final URL url, final @Nullable String hash) {
|
| 317 | HashCode parsedHash = tryParseSha1Hash(hash);
|
| 318 | this.manager.pushPack(id, url, parsedHash);
|
| 319 | }
|
| 320 |
|
| 321 | public void pushLocalPack(final UUID id, final Path path) {
|
| 322 | this.manager.pushLocalPack(id, path);
|
| 323 | }
|
| 324 |
|
| 325 | public void popPack(final UUID id) {
|
| 326 | this.manager.popPack(id);
|
| 327 | }
|
| 328 |
|
| 329 | public void popAll() {
|
| 330 | this.manager.popAll();
|
| 331 | }
|
| 332 |
|
| 333 | private static PackLoadFeedback createPackResponseSender(final Connection connection) {
|
| 334 | return new PackLoadFeedback() {
|
| 335 | @Override
|
| 336 | public void reportUpdate(final UUID id, final PackLoadFeedback.Update result) {
|
| 337 | DownloadedPackSource.LOGGER.debug("Pack {} changed status to {}", id, result);
|
| 338 |
|
| 339 | Action response = switch (result) {
|
| 340 | case ACCEPTED -> Action.ACCEPTED;
|
| 341 | case DOWNLOADED -> Action.DOWNLOADED;
|
| 342 | };
|
| 343 | connection.send(new ServerboundResourcePackPacket(id, response));
|
| 344 | }
|
| 345 |
|
| 346 | @Override
|
| 347 | public void reportFinalResult(final UUID id, final PackLoadFeedback.FinalResult result) {
|
| 348 | DownloadedPackSource.LOGGER.debug("Pack {} changed status to {}", id, result);
|
| 349 |
|
| 350 | Action response = switch (result) {
|
| 351 | case APPLIED -> Action.SUCCESSFULLY_LOADED;
|
| 352 | case DOWNLOAD_FAILED -> Action.FAILED_DOWNLOAD;
|
| 353 | case DECLINED -> Action.DECLINED;
|
| 354 | case DISCARDED -> Action.DISCARDED;
|
| 355 | case ACTIVATION_FAILED -> Action.FAILED_RELOAD;
|
| 356 | };
|
| 357 | connection.send(new ServerboundResourcePackPacket(id, response));
|
| 358 | }
|
| 359 | };
|
| 360 | }
|
| 361 |
|
| 362 | public void configureForServerControl(final Connection connection, final ServerPackManager.PackPromptStatus packPromptStatus) {
|
| 363 | this.packType = PackSource.SERVER;
|
| 364 | this.packFeedback = createPackResponseSender(connection);
|
| 365 | switch (packPromptStatus) {
|
| 366 | case ALLOWED:
|
| 367 | this.manager.allowServerPacks();
|
| 368 | break;
|
| 369 | case DECLINED:
|
| 370 | this.manager.rejectServerPacks();
|
| 371 | break;
|
| 372 | case PENDING:
|
| 373 | this.manager.resetPromptStatus();
|
| 374 | }
|
| 375 | }
|
| 376 |
|
| 377 | public void configureForLocalWorld() {
|
| 378 | this.packType = PackSource.WORLD;
|
| 379 | this.packFeedback = LOG_ONLY_FEEDBACK;
|
| 380 | this.manager.allowServerPacks();
|
| 381 | }
|
| 382 |
|
| 383 | public void allowServerPacks() {
|
| 384 | this.manager.allowServerPacks();
|
| 385 | }
|
| 386 |
|
| 387 | public void rejectServerPacks() {
|
| 388 | this.manager.rejectServerPacks();
|
| 389 | }
|
| 390 |
|
| 391 | public CompletableFuture<Void> waitForPackFeedback(final UUID packId) {
|
| 392 | final CompletableFuture<Void> result = new CompletableFuture<>();
|
| 393 | final PackLoadFeedback original = this.packFeedback;
|
| 394 | this.packFeedback = new PackLoadFeedback() {
|
| 395 | @Override
|
| 396 | public void reportUpdate(final UUID id, final PackLoadFeedback.Update result) {
|
| 397 | original.reportUpdate(id, result);
|
| 398 | }
|
| 399 |
|
| 400 | @Override
|
| 401 | public void reportFinalResult(final UUID id, final PackLoadFeedback.FinalResult status) {
|
| 402 | if (packId.equals(id)) {
|
| 403 | DownloadedPackSource.this.packFeedback = original;
|
| 404 | if (status == PackLoadFeedback.FinalResult.APPLIED) {
|
| 405 | result.complete(null);
|
| 406 | } else {
|
| 407 | result.completeExceptionally(new IllegalStateException("Failed to apply pack " + id + ", reason: " + status));
|
| 408 | }
|
| 409 | }
|
| 410 |
|
| 411 | original.reportFinalResult(id, status);
|
| 412 | }
|
| 413 | };
|
| 414 | return result;
|
| 415 | }
|
| 416 |
|
| 417 | public void cleanupAfterDisconnect() {
|
| 418 | this.manager.popAll();
|
| 419 | this.packFeedback = LOG_ONLY_FEEDBACK;
|
| 420 | this.manager.resetPromptStatus();
|
| 421 | }
|
| 422 |
|
| 423 | @Override
|
| 424 | public void close() throws IOException {
|
| 425 | this.downloadQueue.close();
|
| 426 | }
|
| 427 | }
|
| 428 |
|