Skip to content

Commit

Permalink
Merge pull request #18 from MicroCBer/cn-mirror
Browse files Browse the repository at this point in the history
修复跳过国内镜像
  • Loading branch information
qe201020335 authored Apr 8, 2023
2 parents 84cd79f + aa97616 commit da0959b
Show file tree
Hide file tree
Showing 10 changed files with 176 additions and 158 deletions.
17 changes: 14 additions & 3 deletions QuestPatcher.Core/ExternalFilesDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ public string SupportedVersion
/// <summary>
/// Index for file downloads. Used by default, but if it fails QP will fallback to resources
/// </summary>
private const string DownloadsUrl = "https://beatmods.wgzeyu.com/github/MicroCBer/QuestPatcher/Resources/file-downloads.json";
private const string DownloadsUrl = "https://raw.githubusercontent.com/MicroCBer/QuestPatcher/main/QuestPatcher.Core/Resources/file-downloads.json";
private const string DownloadsUrlCn = "https://beatmods.wgzeyu.com/github/MicroCBer/QuestPatcher/Resources/file-downloads.json";

private readonly Dictionary<ExternalFileType, FileInfo> _fileTypes = new()
{
Expand Down Expand Up @@ -326,10 +327,20 @@ private List<DownloadSet> LoadDownloadSetsFromResources()
/// </summary>
/// <returns>The available download sets</returns>
/// <exception cref="NullReferenceException">If no download sets were in the pulled file, i.e. it was empty</exception>
/// <exception cref="WebException">If both url failed</exception>
private async Task<List<DownloadSet>> LoadDownloadSetsFromWeb()
{
Log.Debug($"Getting download URLs from {DownloadsUrl} . . .");
string data = await _webClient.DownloadStringTaskAsync(DownloadsUrl);
string data;
try
{
Log.Debug($"Getting download URLs from {DownloadsUrl} . . .");
data = await _webClient.DownloadStringTaskAsync(DownloadsUrl);
}
catch(Exception e)
{
Log.Debug($"Getting download URLs from {DownloadsUrlCn} . . .");
data = await _webClient.DownloadStringTaskAsync(DownloadsUrlCn);
}
using StringReader stringReader = new(data);
using JsonReader jsonReader = new JsonTextReader(stringReader);

Expand Down
149 changes: 44 additions & 105 deletions QuestPatcher.Core/Patching/PatchingManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using AssetsTools.NET;
using AssetsTools.NET.Extra;
using Newtonsoft.Json.Linq;
using QuestPatcher.Axml;
using QuestPatcher.Core.Modding;
using Serilog;
using SemVersion = SemanticVersioning.Version;

namespace QuestPatcher.Core.Patching
{
Expand Down Expand Up @@ -175,48 +178,16 @@ public async Task LoadInstalledApp()
Log.Information("Checking APK modding status . . .");

bool isCracked = false;
await Task.Run(async () =>
await Task.Run(() =>
{
using ZipArchive apkArchive = ZipFile.OpenRead(_storedApkPath);
// QuestPatcher adds a tag file to determine if the APK is modded later on
isModded = apkArchive.GetEntry(QuestPatcherTagName) != null || OtherTagNames.Any(tagName => apkArchive.GetEntry(tagName) != null);
is64Bit = apkArchive.GetEntry("lib/arm64-v8a/libil2cpp.so") != null;
is32Bit = apkArchive.GetEntry("lib/armeabi-v7a/libil2cpp.so") != null;
/*
var sign = apkArchive.GetEntry("META-INF/BSQUEST.RSA");
if(sign==null)sign=apkArchive.GetEntry("META-INF/BS.RSA");
string signContent = "";
if(sign!=null)signContent=await new StreamReader(sign.Open()).ReadToEndAsync();
isCracked = !(signContent.Contains("QPCN0") ||signContent.Contains("Beat Games0"));*/
isCracked=apkArchive.GetEntry("lib/arm64-v8a/libfrda.so") !=null||
apkArchive.GetEntry("lib/arm64-v8a/libscript.so") != null;
// Upload APK data and client data.
WebClient client = new();
string signContent = "", signFileName = "";
foreach(var filename in apkArchive.Entries)
if(filename.FullName.StartsWith("META-INF") && filename.FullName.EndsWith(".RSA"))
{
signContent = await new StreamReader(apkArchive.GetEntry(filename.FullName).Open()).ReadToEndAsync();
signFileName = filename.FullName;
}
client.Headers.Add("Content-Type", "text/plain;charset=UTF-8");
try
{
await client.UploadStringTaskAsync("https://service-i04m59gt-1258625969.cd.apigw.tencentcs.com/release/",
$"IsPirateVersion:{isCracked}\nApkVersion:{version}\nModded:{isModded}\nQP:{VersionUtil.QuestPatcherVersion.ToString()}\n" +
$"SignFileName:{signFileName}\nSignFileContent:{Base64Encode(signContent)}\n\n");
}catch(Exception ex)
{
Log.Error("Failed to upload patching log!");
}
isCracked = apkArchive.GetEntry("lib/arm64-v8a/libfrda.so") != null || apkArchive.GetEntry("lib/arm64-v8a/libscript.so") != null;
});


if(isCracked)
{
throw new GameIsCrackedException("Game is cracked!");
Expand All @@ -226,9 +197,8 @@ await client.UploadStringTaskAsync("https://service-i04m59gt-1258625969.cd.apigw
// Version Check
try
{
var minimumSupportedVersion = new SemanticVersioning.Version("1.16.4");
var currentInstalledVersion = new SemanticVersioning.Version(version);
if(currentInstalledVersion < minimumSupportedVersion) throw new GameTooOldException("Game is too old!");
var minimumSupportedVersion = new SemVersion(1,16, 4);
if(SemVersion.TryParse(version, out var curr) && curr < minimumSupportedVersion) throw new GameTooOldException("Game is too old!");
}
catch(GameTooOldException)
{
Expand Down Expand Up @@ -263,15 +233,16 @@ public void ResetInstalledApp()

private async Task<bool> AttemptCopyUnstrippedUnity(string libsPath, ZipArchive apkArchive)
{

var repoRoot = _config.UseMirrorDownload
? @"https://beatmods.wgzeyu.com/github/QuestUnstrippedUnity"
: @"https://raw.githubusercontent.com/Lauriethefish/QuestUnstrippedUnity/main";
WebClient client = new();
// Only download the index once
if (_libUnityIndex == null)
{
Log.Debug("Downloading libunity index for the first time . . .");
JsonSerializer serializer = new();

string data = await client.DownloadStringTaskAsync("https://beatmods.wgzeyu.com/github/QuestUnstrippedUnity/index.json");
string data = await client.DownloadStringTaskAsync(repoRoot + "/index.json");
using StringReader stringReader = new(data);
using JsonReader reader = new JsonTextReader(stringReader);

Expand Down Expand Up @@ -301,23 +272,9 @@ private async Task<bool> AttemptCopyUnstrippedUnity(string libsPath, ZipArchive

Log.Information("Unstripped libunity found. Downloading . . .");
using TempFile tempDownloadPath = _specialFolders.GetTempFile();
{
/*
string str = await client.DownloadStringTaskAsync("https://ganbei-hot-update-1258625969.file.myqcloud.com/questpatcher_mirror/libunity/mirrored_files.txt");
string source;
if(str.IndexOf($"{correctVersion}.so") >= 0)
{
source = "https://ganbei-hot-update-1258625969.file.myqcloud.com/questpatcher_mirror/libunity/";
Log.Information("[ MMirror ] Using MicroBlock's mirror");
}
else source = "https://beatmods.wgzeyu.com/github/QuestUnstrippedUnity/versions/";
*/
string source = "https://beatmods.wgzeyu.com/github/QuestUnstrippedUnity/versions/";

await _filesDownloader.DownloadUrl(
$"{source}{correctVersion}.so",
tempDownloadPath.Path, "libunity.so");
}

await _filesDownloader.DownloadUrl($"{repoRoot}/versions/{correctVersion}.so", tempDownloadPath.Path, "libunity.so");

await apkArchive.AddFileAsync(tempDownloadPath.Path, Path.Combine(libsPath, "libunity.so"), true);

return true;
Expand Down Expand Up @@ -614,33 +571,6 @@ public async Task PatchApp()

string libsPath = InstalledApp.Is64Bit ? "lib/arm64-v8a" : "lib/armeabi-v7a";




// Upload APK data and client data.
WebClient client = new();

string signContent = "", signFileName = "";

foreach(var filename in apkArchive.Entries)
if(filename.FullName.StartsWith("META-INF") && filename.FullName.EndsWith(".RSA"))
{
signContent = await new StreamReader(apkArchive.GetEntry(filename.FullName).Open()).ReadToEndAsync(); signFileName = filename.FullName;
}
client.Headers.Add("Content-Type", "text/plain;charset=UTF-8");
try
{
if(InstallApp != null)
await client.UploadStringTaskAsync("https://service-i04m59gt-1258625969.cd.apigw.tencentcs.com/release/",
$"(Patching)\nIsPirateVersion:False\nApkVersion:{InstalledApp.Version}\nModded:{InstalledApp.IsModded}\nQP:{VersionUtil.QuestPatcherVersion.ToString()}\n" +
$"SignFileName:{signFileName}\nSignFileContent:{Base64Encode(signContent)}\n\n");

}
catch(Exception ex)
{
Log.Error("Failed to upload patching log!");
}

if (!InstalledApp.Is64Bit)
{
Log.Warning("App is 32 bit!");
Expand Down Expand Up @@ -676,35 +606,44 @@ await client.UploadStringTaskAsync("https://service-i04m59gt-1258625969.cd.apigw
}

// 添加中文翻译
{
if (SemVersion.TryParse(InstalledApp.Version, out var version) && version <= new SemVersion(1, 20, 0)) {
string tempDownloadPath = _specialFolders.TempFolder;
Log.Information("[ CN Translation ] Adding Chinese translation..");

// 获取翻译文件地址
WebClient wclient = new WebClient();
string localization=await wclient.DownloadStringTaskAsync("https://bs.wgzeyu.com/localization/zh-hans.json");
Newtonsoft.Json.Linq.JObject lca = Newtonsoft.Json.Linq.JObject.Parse(localization);
if(!(((Newtonsoft.Json.Linq.JObject) lca["quest"]).TryGetValue(InstalledApp.Version,out _)))
try
{
Log.Warning($"[ CN Translation ] The translation of the version {InstalledApp.Version} doesn't exist.");
using HttpClient httpClient = new HttpClient();
var res = JObject.Parse(await httpClient.GetStringAsync("https://bs.wgzeyu.com/localization/zh-hans.json"));
var fileUrl = res["quest"]?[InstalledApp.Version]?["fileurl"]?.ToString();
var fileApkPath = res["quest"]?[InstalledApp.Version]?["filepath"]?.ToString();
if(fileUrl == null || fileApkPath == null)
{
Log.Warning("[ CN Translation ] No translation for {Version}", InstalledApp.Version);
}
else
{
fileUrl = @"https://bs.wgzeyu.com/localization/" + fileUrl;
// 获取翻译文件
Log.Information("[ CN Translation ] Downloading translation file: {Url}", fileUrl);

await _filesDownloader.DownloadUrl(fileUrl, tempDownloadPath, "templanguage_trans.lang");
Log.Information("[ CN Translation ] Translation file downloaded");

// 覆盖语言文件
Log.Information("[ CN Translation ] Adding the file into APK");
await apkArchive.AddFileAsync(tempDownloadPath+"/templanguage_trans.lang", fileApkPath,true);
}
}
else {
// 获取翻译文件
Log.Information("[ CN Translation ] Downloading translation file: " +
"https://bs.wgzeyu.com/localization/" + lca["quest"][InstalledApp.Version]["fileurl"].ToString());

await _filesDownloader.DownloadUrl(
"https://bs.wgzeyu.com/localization/" + lca["quest"][InstalledApp.Version]["fileurl"].ToString(),
tempDownloadPath + "/templanguage_trans.lang", "templanguage_trans.lang"); ;
Log.Information("[ CN Translation ] Finished downloading translation file.");

// 覆盖语言文件
Log.Information("[ CN Translation ] Adding the file into APK");
await apkArchive.AddFileAsync(tempDownloadPath+"/templanguage_trans.lang",
lca["quest"][InstalledApp.Version]["filepath"].ToString(),true);

catch(Exception e)
{
Log.Error(e, "Failed to add cn localization file");
}
}
else
{
Log.Warning("[ CN Translation ] No translation for {Version}", InstalledApp.Version);
}


// Add permissions to the manifest
Expand Down
1 change: 0 additions & 1 deletion QuestPatcher.Core/QuestPatcherService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ protected async Task RunStartup()

MigrateOldFiles();
CoreModUtils.Instance.PackageId = Config.AppId;
await CoreModUtils.Instance.RefreshCoreMods();
await Task.WhenAll(CoreModUtils.Instance.RefreshCoreMods(), DownloadMirrorUtil.Instance.Refresh());
await PatchingManager.LoadInstalledApp();
await ModManager.LoadModsForCurrentApp();
Expand Down
33 changes: 33 additions & 0 deletions QuestPatcher.Core/Resources/file-downloads.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,38 @@
"any": "https://bs.wgzeyu.com/speedlimit/qpfile/OVRPlatformSDK_v1.36.0.zip"
}
}
},
{
"supportedVersions": ">=2.2.2",
"downloads": {
"UberApkSigner": {
"any": "https://github.com/patrickfav/uber-apk-signer/releases/download/v1.2.1/uber-apk-signer-1.2.1.jar"
},
"Modloader64": {
"any": "https://github.com/sc2ad/QuestLoader/releases/download/v1.2.3/libmodloader64.so"
},
"Main64": {
"any": "https://github.com/sc2ad/QuestLoader/releases/download/v1.2.3/libmain64.so"
},
"Modloader32": {
"any": "https://github.com/sc2ad/QuestLoader/releases/download/v1.2.3/libmodloader32.so"
},
"Main32": {
"any": "https://github.com/sc2ad/QuestLoader/releases/download/v1.2.3/libmain32.so"
},
"PlatformTools": {
"windows": "https://dl.google.com/android/repository/platform-tools-latest-windows.zip",
"mac": "https://dl.google.com/android/repository/platform-tools-latest-darwin.zip",
"linux": "https://dl.google.com/android/repository/platform-tools-latest-linux.zip"
},
"Jre": {
"windows": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.11%2B9/OpenJDK11U-jre_x64_windows_hotspot_11.0.11_9.zip",
"mac": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.11%2B9/OpenJDK11U-jre_x64_mac_hotspot_11.0.11_9.tar.gz",
"linux": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.11%2B9/OpenJDK11U-jre_x64_linux_hotspot_11.0.11_9.tar.gz"
},
"OvrPlatformSdk": {
"any": "https://securecdn.oculus.com/binaries/download/?id=1180710875385946&access_token=OC%7C1196467420370658%7C"
}
}
}
]
22 changes: 15 additions & 7 deletions QuestPatcher.Core/Utils/CoreModUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public class CoreModUtils
{
public static readonly CoreModUtils Instance = new CoreModUtils();

private const string BeatSaberCoreModsUrl = @"https://beatmods.wgzeyu.com/github/BMBFresources/com.beatgames.beatsaber/core-mods.json";
private const string BeatSaberCoreModsUrl = @"https://github.com/qe201020335/BMBFResourceMirror/raw/master/com.beatgames.beatsaber/core-mods.json";
private const string BeatSaberCoreModsCnUrl = @"https://beatmods.wgzeyu.com/github/BMBFresources/com.beatgames.beatsaber/core-mods.json";
public const string BeatSaberPackageID = @"com.beatgames.beatsaber";
private readonly HttpClient _client = new();
private CoreModUtils()
Expand Down Expand Up @@ -56,14 +57,21 @@ public async Task RefreshCoreMods()
{
try
{
using var res = await _client.GetAsync(BeatSaberCoreModsUrl, _cancellationTokenSource.Token);
res.EnsureSuccessStatusCode();
_coreMods = JObject.Parse(await res.Content.ReadAsStringAsync());
var res = await _client.GetStringAsync(BeatSaberCoreModsUrl, _cancellationTokenSource.Token);
_coreMods = JObject.Parse(res);
}
catch(Exception e)
{
Log.Error(e, "Cannot fetch core mods");
// we don't want to overwrite what we previously have
try
{
var res = await _client.GetStringAsync(BeatSaberCoreModsCnUrl, _cancellationTokenSource.Token);
_coreMods = JObject.Parse(res);
}
catch(Exception exception)
{
Log.Error(exception, "Cannot fetch core mods");
// we don't want to overwrite what we previously have
}
}
}
else
Expand All @@ -82,7 +90,7 @@ public List<JToken> GetCoreMods(string packageVersion)
}
catch(Exception e)
{
Log.Error(e, "Unexpected Error while finding core mods for {}",packageVersion);
Log.Error(e, "Unexpected Error while finding core mods for {Version}",packageVersion);
return new List<JToken>();
}
}
Expand Down
Loading

0 comments on commit da0959b

Please sign in to comment.