feat: Implement caching of SHA1's and fall back to old loading bar when offline (#13)

This commit is contained in:
Eva Isabella Luna 2025-06-15 01:41:29 -06:00 committed by GitHub
commit 29b9e2233f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 107 additions and 20 deletions

View File

@ -9,6 +9,7 @@ import android.graphics.Color;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.NetworkInfo;
import android.net.Uri; import android.net.Uri;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
@ -276,6 +277,10 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
} }
private void performLogin(MinecraftAccount minecraftAccount){ private void performLogin(MinecraftAccount minecraftAccount){
// Logging in when there's no internet is useless. This should really be turned into a network callback though.
if(!Tools.isOnline(getContext())){
return;
}
if(minecraftAccount.isLocal()) return; if(minecraftAccount.isLocal()) return;
mLoginBarPaint.setColor(getResources().getColor(R.color.minebutton_color)); mLoginBarPaint.setColor(getResources().getColor(R.color.minebutton_color));

View File

@ -21,6 +21,8 @@ import android.content.res.Resources;
import android.database.Cursor; import android.database.Cursor;
import android.hardware.Sensor; import android.hardware.Sensor;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
@ -1429,6 +1431,18 @@ public final class Tools {
OBSOLETE_RESOURCES_PATH = DIR_GAME_NEW + "/resources"; OBSOLETE_RESOURCES_PATH = DIR_GAME_NEW + "/resources";
} }
private static NetworkInfo getActiveNetworkInfo(Context ctx) {
ConnectivityManager connMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo; // This can return null when there is no wifi or data connected
}
public static boolean isOnline(Context ctx) {
NetworkInfo info = getActiveNetworkInfo(ctx);
if(info == null) return false;
return (info.isConnected());
}
public static boolean isDemoProfile(Context ctx){ public static boolean isDemoProfile(Context ctx){
MinecraftAccount currentProfile = PojavProfile.getCurrentProfileContent(ctx, null); MinecraftAccount currentProfile = PojavProfile.getCurrentProfileContent(ctx, null);
return currentProfile != null && currentProfile.isDemo(); return currentProfile != null && currentProfile.isDemo();

View File

@ -76,14 +76,18 @@ public class DownloadMirror {
* @param urlInput The original (Mojang) URL for the download * @param urlInput The original (Mojang) URL for the download
* @return the length of the file denoted by the URL in bytes, or -1 if not available * @return the length of the file denoted by the URL in bytes, or -1 if not available
*/ */
public static long getContentLengthMirrored(int downloadClass, String urlInput) throws IOException { public static long getContentLengthMirrored(int downloadClass, String urlInput){
long length = DownloadUtils.getContentLength(getMirrorMapping(downloadClass, urlInput)); try {
if(length < 1) { long length = DownloadUtils.getContentLength(getMirrorMapping(downloadClass, urlInput));
Log.w("DownloadMirror", "Unable to get content length from mirror"); if (length < 1) {
Log.i("DownloadMirror", "Falling back to default source"); Log.w("DownloadMirror", "Unable to get content length from mirror");
return DownloadUtils.getContentLength(urlInput); Log.i("DownloadMirror", "Falling back to default source");
}else { return DownloadUtils.getContentLength(urlInput);
return length; } else {
return length;
}
} catch (IOException ignored) { // If error happens, fallback to old file counter instead of size. This shouldn't really happen unless offline though.
return -1L;
} }
} }

View File

@ -3,6 +3,9 @@ package net.kdt.pojavlaunch.tasks;
import static net.kdt.pojavlaunch.PojavApplication.sExecutorService; import static net.kdt.pojavlaunch.PojavApplication.sExecutorService;
import android.app.Activity; import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log; import android.util.Log;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -25,9 +28,12 @@ import net.kdt.pojavlaunch.value.DependentLibrary;
import net.kdt.pojavlaunch.value.MinecraftClientInfo; import net.kdt.pojavlaunch.value.MinecraftClientInfo;
import net.kdt.pojavlaunch.value.MinecraftLibraryArtifact; import net.kdt.pojavlaunch.value.MinecraftLibraryArtifact;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -56,6 +62,7 @@ public class MinecraftDownloader {
private static final ThreadLocal<byte[]> sThreadLocalDownloadBuffer = new ThreadLocal<>(); private static final ThreadLocal<byte[]> sThreadLocalDownloadBuffer = new ThreadLocal<>();
private boolean isLocalProfile = false; private boolean isLocalProfile = false;
private boolean isOnline;
/** /**
* Start the game version download process on the global executor service. * Start the game version download process on the global executor service.
@ -65,11 +72,13 @@ public class MinecraftDownloader {
* @param listener The download status listener * @param listener The download status listener
*/ */
public void start(@Nullable Activity activity, @Nullable JMinecraftVersionList.Version version, public void start(@Nullable Activity activity, @Nullable JMinecraftVersionList.Version version,
@NonNull String realVersion, // this was there for a reason @NonNull String realVersion,
@NonNull AsyncMinecraftDownloader.DoneListener listener) { @NonNull AsyncMinecraftDownloader.DoneListener listener) {
if(activity != null){ if(activity != null){
isLocalProfile = Tools.isLocalProfile(activity); isLocalProfile = Tools.isLocalProfile(activity);
isOnline = Tools.isOnline(activity);
Tools.switchDemo(Tools.isDemoProfile(activity)); Tools.switchDemo(Tools.isDemoProfile(activity));
} else { } else {
isLocalProfile = true; isLocalProfile = true;
Tools.switchDemo(true); Tools.switchDemo(true);
@ -77,14 +86,32 @@ public class MinecraftDownloader {
sExecutorService.execute(() -> { sExecutorService.execute(() -> {
try { try {
if(isLocalProfile){ if(isLocalProfile || !isOnline) {
throw new RuntimeException("Download failed. Please make sure you are logged in with a Microsoft Account."); String versionMessage = realVersion; // Use provided version unless we find its a modded instance
}
// See if provided version is a modded version and if that version depends on another jar, check for presence of both jar's .json.
try {
// This reads the .json associated with the provided version. If it fails, we can assume it's not installed.
File providedJsonFile = new File(Tools.DIR_HOME_VERSION + "/" + realVersion + "/" + realVersion + ".json");
JMinecraftVersionList.Version providedJson = Tools.GLOBAL_GSON.fromJson(Tools.read(providedJsonFile.getAbsolutePath()), JMinecraftVersionList.Version.class);
// This checks if running modded version that depends on other jars, so we use that for the error message.
File vanillaJsonFile = new File(Tools.DIR_HOME_VERSION + "/" + providedJson.inheritsFrom + "/" + providedJson.inheritsFrom + ".json");
versionMessage = providedJson.inheritsFrom != null ? providedJson.inheritsFrom : versionMessage;
// Ensure they're both not some 0 byte corrupted json
if (providedJsonFile.length() == 0 || vanillaJsonFile.exists() && vanillaJsonFile.length() == 0){
throw new RuntimeException("Minecraft "+versionMessage+ " is needed by " +realVersion); }
listener.onDownloadDone();
} catch (Exception e) {
String tryagain = !isOnline ? "Please ensure you have an internet connection" : "Please try again on your Microsoft Account";
Tools.showErrorRemote(versionMessage + " is not currently installed. "+ tryagain, e);
}
}else {
downloadGame(activity, version, realVersion); downloadGame(activity, version, realVersion);
listener.onDownloadDone(); listener.onDownloadDone();
}catch (UnknownHostException e){ }
Log.i("DownloadMirror", e.toString());
Tools.showErrorRemote("Can't download Minecraft, no internet connection found", e);
}catch (Exception e) { }catch (Exception e) {
listener.onDownloadFailed(e); listener.onDownloadFailed(e);
} }
@ -473,18 +500,49 @@ public class MinecraftDownloader {
* Since Minecraft libraries are stored in maven repositories, try to use * Since Minecraft libraries are stored in maven repositories, try to use
* this when downloading libraries without hashes in the json. * this when downloading libraries without hashes in the json.
*/ */
private void tryGetLibrarySha1() { private void tryGetLibrarySha1() throws IOException {
File sha1CacheDir = new File(Tools.DIR_CACHE + "/sha1hashes");
File cacheFile = new File(sha1CacheDir.getAbsolutePath() + FileUtils.getFileName(mTargetUrl) + ".sha");
// Only use cache when its offline. No point in having cache invalidation now!
if (!isOnline || !LauncherPreferences.PREF_CHECK_LIBRARY_SHA) { // Well not only offlines..this setting speeds up launch times at least!
try (BufferedReader cacheFileReader = new BufferedReader(new FileReader(cacheFile))) {
mTargetSha1 = cacheFileReader.readLine();
if (mTargetSha1 != null) {
Log.i("MinecraftDownloader", "Reading Hash from cache: " + mTargetSha1 + " from " + cacheFile);
} else if (cacheFile.exists()) {
Log.i("MinecraftDownloader", "Deleting invalid hash from cache: " + cacheFile);
cacheFile.delete();
}
} catch (FileNotFoundException ignored) {
mTargetSha1 = null;
Log.w("MinecraftDownloader", "Failed to read hash for " + cacheFile);
}
return;
}
String resultHash = null; String resultHash = null;
try { try {
resultHash = downloadSha1(); resultHash = downloadSha1();
// The hash is a 40-byte download. // The hash is a 40-byte download.
mInternetUsageCounter.getAndAdd(40); mInternetUsageCounter.getAndAdd(40);
}catch (IOException e) { } catch (IOException e) {
Log.i("MinecraftDownloader", "Failed to download hash", e); Log.i("MinecraftDownloader", "Failed to download hash", e);
if (cacheFile.exists() && new BufferedReader(new FileReader(cacheFile)).readLine() == null) {
Log.i("MinecraftDownloader", "Deleting failed hash download from cache: " + cacheFile);
cacheFile.delete();
}
} }
if(resultHash != null) { if (resultHash != null) {
Log.i("MinecraftDownloader", "Got hash: "+resultHash+ " for "+FileUtils.getFileName(mTargetUrl)); Log.i("MinecraftDownloader", "Got hash: " + resultHash + " for " + FileUtils.getFileName(mTargetUrl));
mTargetSha1 = resultHash; mTargetSha1 = resultHash;
if (!sha1CacheDir.exists()) {
sha1CacheDir.mkdir(); // If mkdir() fails, something went wrong with initializing /data/data/. mkdirs() isn't used on purpose
}
try (FileWriter writeHash = new FileWriter(cacheFile)) {
Log.i("MinecraftDownloader", "Saving hash: " + resultHash + " for " + FileUtils.getFileName(mTargetUrl) + " to " + cacheFile);
writeHash.write(resultHash);
}
} }
} }

View File

@ -61,6 +61,12 @@ public class DownloadUtils {
FileUtils.ensureParentDirectory(out); FileUtils.ensureParentDirectory(out);
try (FileOutputStream fileOutputStream = new FileOutputStream(out)) { try (FileOutputStream fileOutputStream = new FileOutputStream(out)) {
download(url, fileOutputStream); download(url, fileOutputStream);
} catch (IOException e) {
if (out.length() < 1) { // Only delete it if file is 0 bytes cause this file might already be downloaded and something else went wrong.
Log.i("DownloadUtils", "Cleaning up failed download: " + out.getAbsolutePath());
out.delete();
throw e;
}
} }
} }