private async Task<bool> LaunchGame(MCVersion v, bool KeepLauncherOpen) { try { ViewModels.LauncherModel.Default.CurrentState = ViewModels.LauncherModel.StateChange.isLaunching; var pkg = await AppDiagnosticInfo.RequestInfoForPackageAsync(MINECRAFT_PACKAGE_FAMILY); AppActivationResult activationResult = null; if (pkg.Count > 0) activationResult = await pkg[0].LaunchAsync(); System.Diagnostics.Debug.WriteLine("App launch finished!"); if (KeepLauncherOpen && activationResult != null) GetGameProcess(activationResult); if (KeepLauncherOpen == false) { await Application.Current.Dispatcher.InvokeAsync(() => { Application.Current.MainWindow.Close(); }); return true; } else { ViewModels.LauncherModel.Default.CurrentState = ViewModels.LauncherModel.StateChange.None; return false; } } catch (Exception e) { ViewModels.LauncherModel.Default.CurrentState = ViewModels.LauncherModel.StateChange.None; System.Diagnostics.Debug.WriteLine("App launch failed:\n" + e.ToString()); ErrorScreenShow.errormsg("Error_AppLaunchFailed_Title", "Error_AppLaunchFailed", e); throw e; } }
/// <summary> /// 联网获取指定版本所有的FABRIC /// </summary> /// <param name="version">要搜索的版本</param> /// <returns>Forge列表</returns> public async Task <List <JWFabric> > GetFabricList(MCVersion version) { string json = await HttpRequesterAPI.HttpGetStringAsync(FabricListVEURL); var e = JsonConvert.DeserializeObject <List <JWFabric> >(json); string ver; if (string.IsNullOrWhiteSpace(version.InheritsVersion)) { ver = version.ID; } else { ver = version.InheritsVersion; } var a = e.Where(b => b.Version == ver).ToList(); if (a.Count == 0) { return(null); } json = await HttpRequesterAPI.HttpGetStringAsync(FabricListURL); e = JsonConvert.DeserializeObject <List <JWFabric> >(json); return(e); }
private async Task StartAsync(CommandContext commandContext, string version) { const string serverFolder = @"C:\Users\Nick\Desktop\Minecraft Server"; string defaultVersion = Instance.MCVersions.Single(a => a.Value.Default).Key; if (string.IsNullOrWhiteSpace(version)) { version = defaultVersion; await commandContext.RespondAsync($"You did not specify which version, therefore I'm starting {defaultVersion} MC."); await MCInfoAsync(commandContext); } if (Instance.MCVersions.ContainsKey(version)) { MCVersion mcVersion = Instance.MCVersions[version]; string responseMessage = $"Starting {version} MC Server"; await commandContext.RespondAsync(responseMessage); string directory = Path.Join(serverFolder, mcVersion.FolderName); string botStartFile = Path.Join(directory, "botStart.bat"); ProcessStartInfo processStartInfo = new ProcessStartInfo(botStartFile) { WindowStyle = ProcessWindowStyle.Minimized, WorkingDirectory = directory }; Process.Start(processStartInfo); } else { await commandContext.RespondAsync($"Unable to find MC Version '{version}'"); await MCInfoAsync(commandContext); } }
private async Task UnregisterPackage(MCVersion v, string gameDir, bool reRegisterMode) { foreach (var pkg in new PackageManager().FindPackages(MINECRAFT_PACKAGE_FAMILY)) { string location = GetPackagePath(pkg); if (location == "" || location == gameDir) { if (location == gameDir && reRegisterMode) { System.Diagnostics.Debug.WriteLine("Skipping package removal - same path: " + pkg.Id.FullName + " " + location); return; } System.Diagnostics.Debug.WriteLine("Removing package: " + pkg.Id.FullName); ViewModels.LauncherModel.Default.DeploymentPackageName = pkg.Id.FullName; ViewModels.LauncherModel.Default.CurrentState = ViewModels.LauncherModel.StateChange.isRemovingPackage; if (!pkg.IsDevelopmentMode) { await DeploymentProgressWrapper(v, new PackageManager().RemovePackageAsync(pkg.Id.FullName, RemovalOptions.PreserveApplicationData)); } else { System.Diagnostics.Debug.WriteLine("Package is in development mode"); await DeploymentProgressWrapper(v, new PackageManager().RemovePackageAsync(pkg.Id.FullName, RemovalOptions.PreserveApplicationData)); } System.Diagnostics.Debug.WriteLine("Removal of package done: " + pkg.Id.FullName); ViewModels.LauncherModel.Default.DeploymentPackageName = ""; ViewModels.LauncherModel.Default.CurrentState = ViewModels.LauncherModel.StateChange.None; } } }
public async Task <JAssets> GetAssetsAsync(MCVersion version) { return(await Task.Factory.StartNew(() => { return assetsReader.GetAssets(version); })); }
/// <summary> /// 联网获取指定版本所有的FORGE /// </summary> /// <param name="version">要搜索的版本</param> /// <returns>Forge列表</returns> public async Task <List <JWForge> > GetForgeList(MCVersion version) { string json = await HttpRequesterAPI.HttpGetStringAsync(string.Format("{0}/{1}", ForgeListURL, version.ID)); var e = JsonConvert.DeserializeObject <List <JWForge> >(json); return(e); }
/// <summary> /// 联网获取指定版本所有的Liteloader /// </summary> /// <param name="version">要搜索的版本</param> /// <returns>Liteloader列表</returns> public async Task <JWLiteloader> GetLiteloaderList(MCVersion version) { string json = await HttpRequesterAPI.HttpGetStringAsync(string.Format("{0}/?mcversion={1}", LiteloaderListURL, version.ID)); var e = JsonConvert.DeserializeObject <JWLiteloader>(json); return(e); }
/// <summary> /// 获取全部丢失的文件下载任务 /// </summary> /// <param name="source">下载源</param> /// <param name="core">使用的核心</param> /// <param name="version">检查的版本</param> /// <returns></returns> public async static Task <List <DownloadTask> > GetLostDependDownloadTaskAsync(DownloadSource source, LaunchHandler core, MCVersion version, MetroWindow window) { var lostLibs = GetLostLibs(core, version); var lostNatives = GetLostNatives(core, version); List <DownloadTask> tasks = new List <DownloadTask>(); if (IsLostJarCore(core, version)) { if (version.Jar == null) { tasks.Add(GetDownloadUrl.GetCoreJarDownloadTask(source, version, core)); } } if (version.InheritsVersion != null) { string innerJsonPath = core.GetJsonPath(version.InheritsVersion); string innerJsonStr; if (!File.Exists(innerJsonPath)) { innerJsonStr = await HttpRequesterAPI.HttpGetStringAsync(GetDownloadUrl.GetCoreJsonDownloadURL(source, version.InheritsVersion)); if (innerJsonStr == null) { await window.ShowMessageAsync("检查错误", "检查源错误,请切换下载源后重试"); return(new List <DownloadTask>()); } string jsonFolder = Path.GetDirectoryName(innerJsonPath); if (!Directory.Exists(jsonFolder)) { Directory.CreateDirectory(jsonFolder); } File.WriteAllText(innerJsonPath, innerJsonStr); } else { innerJsonStr = File.ReadAllText(innerJsonPath); } MCVersion innerVer = core.JsonToVersion(innerJsonStr); if (innerVer != null) { tasks.AddRange(await GetLostDependDownloadTaskAsync(source, core, innerVer, window)); } } foreach (var item in lostLibs) { tasks.Add(GetDownloadUrl.GetLibDownloadTask(source, item)); } foreach (var item in lostNatives) { tasks.Add(GetDownloadUrl.GetNativeDownloadTask(source, item)); } return(tasks); }
public async Task Download(MCVersion version, string updateIdentity, string revisionNumber, string destination, DownloadProgress progress, CancellationToken cancellationToken) { string link = await GetDownloadUrl(updateIdentity, revisionNumber); if (link == null) { throw new ArgumentException(string.Format("Bad updateIdentity for {0}", version.DisplayName)); } System.Diagnostics.Debug.WriteLine("Resolved download link: " + link); await DownloadFile(link, destination, progress, cancellationToken); }
public static bool IsLostJarCore(LaunchHandler core, MCVersion version) { if (version.InheritsVersion == null) { string jarPath = core.GetJarPath(version); return(!File.Exists(jarPath)); } else { return(false); } }
/// <summary> /// 获取版本是否丢失任何库文件 /// </summary> /// <param name="core">启动核心</param> /// <param name="version">检查的版本</param> /// <returns>是否丢失任何库文件</returns> public static bool IsLostAnyLibs(LaunchHandler core, MCVersion version) { foreach (var item in version.Libraries) { string path = core.GetLibraryPath(item); if (!File.Exists(path)) { return(true); } } return(false); }
public Task <VersionManifestDefinition> GetVersion(MCVersion v) { JsonSerializer js = new JsonSerializer(); if (File.Exists(Path.Combine("data", "versions", v.ID, v.ID + ".json"))) { using (var fs = File.OpenRead(Path.Combine("data", "versions", v.ID, v.ID + ".json"))) using (StreamReader sr = new StreamReader(fs)) using (JsonTextReader jr = new JsonTextReader(sr)) return(Task.FromResult(js.Deserialize <VersionManifestDefinition>(jr))); } throw new MCDownloadException("Couldn't find version in local files"); }
public override void Download() { ServicePointManager.DefaultConnectionLimit = 1000; MCVersion.InstallLaunchWrapper(); var url = this.Url; var versionText = string.Format("{0}_{1}_{2}", this.MCVersion, this.Type, this.Patch); var jarname = "Optifine-" + versionText + ".jar"; var dirpath = "optifine\\Optifine\\" + versionText + "\\"; var downloadDirPath = LauncherMain.Instance.Settings.MinecraftFolderName + "libraries\\" + dirpath; if (!Directory.Exists(downloadDirPath)) { Directory.CreateDirectory(downloadDirPath); } var path = dirpath + jarname; var downloadPath = downloadDirPath + jarname; var manifest = MinecraftManifest.AnalyzeFromVersion(this.MCVersion); using (var wc = new WebClient()) { OnProgressChanged("开始下载。。", 0); wc.DownloadProgressChanged += (sender, args) => OnProgressChanged(null, (int)(args.ProgressPercentage * 0.8)); Task downloadTask = wc.DownloadFileTaskAsync(url, downloadPath); while (!downloadTask.IsCompleted) { Thread.Sleep(500); } } OnProgressChanged("正在添加依赖项。。。", 80); var library = new MinecraftLibrary(); library.name = dirpath.Substring(0, dirpath.Length - 1).Replace('\\', ':'); library.downloads = new LibraryDownloads(); library.downloads.artifact = new DownloadInfo(); library.downloads.artifact.path = path.Replace('\\', '/'); library.downloads.artifact.url = url; manifest.libraries.Add(library); if (manifest.minecraftArguments == null) { manifest.arguments.game.Add("--tweakClass"); manifest.arguments.game.Add("optifine.OptiFineTweaker"); } else { manifest.minecraftArguments += " --tweakClass optifine.OptiFineTweaker"; } OnProgressChanged(null, 100); MCVersion.SaveManifest(manifest); }
public ServerLegacyServerListPong( bool isBeta, int protocolVersion, MCVersion minecraftVersion, string messageOfTheDay, int currentPlayerCount, int maxPlayers) { IsBeta = isBeta; ProtocolVersion = protocolVersion; MinecraftVersion = minecraftVersion ?? throw new ArgumentNullException(nameof(minecraftVersion)); MessageOfTheDay = messageOfTheDay ?? throw new ArgumentNullException(nameof(messageOfTheDay)); CurrentPlayerCount = currentPlayerCount; MaxPlayers = maxPlayers; }
/// <summary> /// 获取版本丢失的natives文件 /// </summary> /// <param name="core">所使用的核心</param> /// <param name="version">要检查的版本</param> /// <returns>返回Key为路径,value为native实例的集合</returns> public static Dictionary <string, Native> GetLostNatives(LaunchHandler core, MCVersion version) { Dictionary <string, Native> lostNatives = new Dictionary <string, Native>(); foreach (var item in version.Natives) { string path = core.GetNativePath(item); if (lostNatives.ContainsKey(path)) { continue; } else if (!File.Exists(path)) { lostNatives.Add(path, item); } } return(lostNatives); }
private static async Task MCInfoAsync(CommandContext commandContext) { StringBuilder stringBuilder = new StringBuilder(); string ipAddress = await GetIPAddressAsync(); foreach (KeyValuePair <string, MCVersion> nameAndMCVersion in Instance.MCVersions) { MCVersion mcVersion = nameAndMCVersion.Value; stringBuilder.AppendLine($"**[{nameAndMCVersion.Key}]({mcVersion.DownloadURL})** ({ipAddress}{(mcVersion.Port == 25565 ? "" : $":{mcVersion.Port}")})"); stringBuilder.AppendLine($"*{mcVersion.Description}*"); stringBuilder.AppendLine(); } DiscordEmbedBuilder discordEmbedBuilder = Instance.GetDiscordEmbedBuilder() .WithTitle("Current Minecraft Versions") .WithDescription(stringBuilder.ToString().Trim()); await commandContext.RespondAsync(embed : discordEmbedBuilder.Build()); }
public JAssets GetAssets(MCVersion version) { try { lock (locker) { string assetsPath = handler.GetAssetsIndexPath(version.Assets); if (!File.Exists(assetsPath)) { return(null); } var ja = GetAssetsByJson(File.ReadAllText(assetsPath)); return(ja); } } catch (Exception) { return(null); } }
private async Task ReRegisterPackage(MCVersion v, string gameDir) { try { await UnregisterPackage(v, gameDir, true); System.Diagnostics.Debug.WriteLine("Registering package"); string manifestPath = Path.Combine(gameDir, "AppxManifest.xml"); ViewModels.LauncherModel.Default.DeploymentPackageName = GetPackageNameFromMainifest(manifestPath); ViewModels.LauncherModel.Default.CurrentState = ViewModels.LauncherModel.StateChange.isRegisteringPackage; await DeploymentProgressWrapper(v, new PackageManager().RegisterPackageAsync(new Uri(manifestPath), null, DeploymentOptions.DevelopmentMode)); System.Diagnostics.Debug.WriteLine("App re-register done!"); ViewModels.LauncherModel.Default.DeploymentPackageName = ""; ViewModels.LauncherModel.Default.CurrentState = ViewModels.LauncherModel.StateChange.None; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("App re-register failed:\n" + e.ToString()); ErrorScreenShow.errormsg("Error_AppReregisterFailed_Title", "Error_AppReregisterFailed", e); throw e; } }
public VivecraftVersion(Repository repository) { Repository = repository; Name = repository.Name; MCVersion = VersionRegex.regex.Match(repository.Description).Value; System.Version.TryParse(MCVersion.Remove(".X"), out var _ver); _MCVersion = _ver; Releases = GithubCl.GetAllReleasesForRepository(MainForm.ghClient, repository.Owner.Login, repository.Name); if (Releases.Count > 0) { foreach (var asset in Releases[0].Assets) { if (asset.Name.Contains("non", StringComparison.OrdinalIgnoreCase)) { NonVRInstaller = asset; } else { VRInstaller = asset; } } } Logger.Debug("New VivecraftVersion: %s", this.ToJson()); }
private async Task DeploymentProgressWrapper(MCVersion version, IAsyncOperationWithProgress<DeploymentResult, DeploymentProgress> t) { TaskCompletionSource<int> src = new TaskCompletionSource<int>(); t.Progress += (v, p) => { System.Diagnostics.Debug.WriteLine("Deployment progress: " + p.state + " " + p.percentage + "%"); if (Properties.LauncherSettings.Default.ShowAdvancedInstallDetails) ViewModels.LauncherModel.Default.CurrentProgress = Convert.ToInt64(p.percentage); if (Properties.LauncherSettings.Default.ShowAdvancedInstallDetails) ViewModels.LauncherModel.Default.TotalProgress = ViewModels.LauncherModel.DeploymentMaximum; }; t.Completed += (v, p) => { if (p == AsyncStatus.Error) { System.Diagnostics.Debug.WriteLine("Deployment failed: " + v.GetResults().ErrorText); src.SetException(new Exception("Deployment failed: " + v.GetResults().ErrorText)); } else { System.Diagnostics.Debug.WriteLine("Deployment done: " + p); src.SetResult(1); } }; await src.Task; }
/// <summary> /// 获取游戏核心下载 /// </summary> /// <param name="downloadSource">下载源</param> /// <param name="version">版本</param> /// <param name="core">核心</param> /// <returns></returns> public static DownloadTask GetCoreJarDownloadTask(DownloadSource downloadSource, MCVersion version, LaunchHandler core) { string to = core.GetJarPath(version); string from = GetCoreJarDownloadURL(downloadSource, version); DownloadTask downloadTask = new DownloadTask("游戏版本核心Jar文件", from, to); if (!string.IsNullOrWhiteSpace(version.Downloads?.Client?.SHA1)) { downloadTask.Checker = new SHA1Checker() { CheckSum = version.Downloads.Client.SHA1, FilePath = to }; } return(downloadTask); }
public override void Download() { bool NeedBranchName = !NetUtils.IsUrlExists(Url); if (NeedBranchName) { Url = string.Format( "http://files.minecraftforge.net/maven/net/minecraftforge/forge/{0}-{1}-{0}/forge-{0}-{1}-{0}-universal.jar", MCVersion.VersionName, ForgeVersion ); } if (UseBMCL) { Url = Url.Replace("files.minecraftforge.net", "bmclapi2.bangbang93.com"); } OnProgressChanged("正在检查launchwrapper安装情况并确保安装", 0); MCVersion.InstallLaunchWrapper(); string jarfile, folder; if (NeedBranchName) { jarfile = string.Format("forge-{0}-{1}-{0}.jar", this.MCVersion.VersionName, this.ForgeVersion); folder = string.Format("net/minecraftforge/forge/{0}-{1}-{0}/", this.MCVersion.VersionName, this.ForgeVersion); } else { jarfile = string.Format("forge-{0}-{1}.jar", this.MCVersion.VersionName, this.ForgeVersion); folder = string.Format("net/minecraftforge/forge/{0}-{1}/", this.MCVersion.VersionName, this.ForgeVersion); } var location = folder + jarfile; var realLocation = LauncherMain.Instance.Settings.MinecraftFolderName + "libraries\\" + location.Replace('/', '\\'); var realFolder = LauncherMain.Instance.Settings.MinecraftFolderName + "libraries\\" + folder.Replace('/', '\\'); if (!Directory.Exists(realFolder)) { Directory.CreateDirectory(realFolder); } using (var wc = new WebClient()) { OnProgressChanged("开始下载" + jarfile, 0); bool downloaded = false; wc.DownloadFileCompleted += (o, e) => { downloaded = true; wc.Dispose(); }; wc.DownloadProgressChanged += (o, e) => OnProgressChanged(null, e.ProgressPercentage); wc.DownloadFileAsync(new Uri(this.Url), realLocation); while (!downloaded) { Thread.Sleep(100); } } var zip = ZipFile.Open(realLocation, ZipArchiveMode.Read); var versionlistentry = zip.GetEntry("version.json"); var sr = new StreamReader(versionlistentry.Open()); var json = sr.ReadToEnd(); sr.Close(); zip.Dispose(); var matches = Regex.Matches(json, "\"name\"\\s*:\\s*\"(.*?)\""); var manifest = MinecraftManifest.AnalyzeFromVersion(MCVersion); int needDownload = 0; int downloadedCount = 0; foreach (Match match in matches) { var groups = EnumeratorUtils.MakeListFromEnumerator(match.Groups.GetEnumerator()); var libname = ((Group)groups[1]).Value; var names = new List <string>(libname.Split(':')); if (names[1] != "launchwrapper") { manifest.libraries.RemoveAll(m => { var ns = m.name.Split(':'); return(ns[1] == names[1]); }); var fnames = names[0].Split('.'); names.RemoveAt(0); names.InsertRange(0, fnames); string url; if (this.UseBMCL) { url = "http://bmclapi2.bangbang93.com/maven/"; } else { if (Regex.IsMatch( json, string.Format( "\"name\"\\s*:\\s*\"{0}\"\\n" + "\\s*?\"url\"\\s*:\\s*\"http://files\\.minecraftforge\\.net/maven/\"", libname.Replace(".", "\\.") ) )) { url = "http://files.minecraftforge.net/maven/"; } else { url = "https://libraries.minecraft.net/"; } } url += string.Join("/", names); var jarname = names[names.Count - 2] + "-" + names[names.Count - 1] + ".jar"; url += "/" + jarname; var localDir = LauncherMain.Instance.Settings.MinecraftFolderName + "libraries\\" + string.Join("\\", names) + "\\"; if (!Directory.Exists(localDir)) { Directory.CreateDirectory(localDir); } var localLoc = localDir + jarname; if (!File.Exists(localLoc)) { var wc = new WebClient(); wc.DownloadFileCompleted += (o, e) => { downloadedCount++; OnProgressChanged(jarname + "已下载", (int)(downloadedCount / (double)needDownload * 100)); wc.Dispose(); }; wc.DownloadProgressChanged += (o, e) => Debug.WriteLine(string.Format("{0} Downloaded {1}", jarname, e.ProgressPercentage)); wc.DownloadFileAsync(new Uri(url), localLoc); } var library = new MinecraftLibrary { name = libname }; manifest.libraries.Add(library); needDownload++; } } while (needDownload != downloadedCount) { Thread.Sleep(100); } if (manifest.arguments == null) { manifest.minecraftArguments += " --tweakClass cpw.mods.fml.common.launcher.FMLTweaker"; } else { manifest.arguments.game.Add("--tweakClass"); manifest.arguments.game.Add("cpw.mods.fml.common.launcher.FMLTweaker"); } MCVersion.SaveManifest(manifest); }
/// <summary> /// 获取Fabric下载 /// </summary> /// <param name="downloadSource">下载源</param> /// <param name="forge">Forge信息</param> /// <returns></returns> public static DownloadTask GetFabricDownloadURL(DownloadSource downloadSource, APIModules.JWFabric fabric, MCVersion version) { string local = PathManager.TempDirectory + "\\fabric-installer-0.6.1.45.jar"; DownloadTask dt = new DownloadTask(App.GetResourceString("String.NewDownloadTaskWindow.Core.Fabric"), @"https://maven.fabricmc.net/net/fabricmc/fabric-installer/0.6.1.45/fabric-installer-0.6.1.45.jar", local); dt.Todo = new Func <ProgressCallback, CancellationToken, Exception>((callback, cancelToken) => { try { IInstaller installer = new FabricInstaller(local, new CommonInstallOptions() { GameRootPath = App.Handler.GameRootPath, IsClient = true, DownloadSource = App.Config.MainConfig.Download.DownloadSource, Java = App.Handler.Java, obj = new APIModules.TwoObj { fabric = fabric, version = version } }); installer.BeginInstall(callback, cancelToken).Wait(); return(null); } catch (Exception ex) { return(ex); } }); return(dt); }
/// <summary> /// 获取Forge下载 /// </summary> /// <param name="downloadSource">下载源</param> /// <param name="forge">Forge信息</param> /// <returns></returns> public static DownloadTask GetForgeDownloadURL(DownloadSource downloadSource, APIModules.JWForge forge, MCVersion mc) { string local = PathManager.TempDirectory + "\\forge-" + forge.Build + ".jar"; string Source = BMCLUrl; switch (downloadSource) { case DownloadSource.Mojang: Source = BMCLUrl; break; case DownloadSource.BMCLAPI: Source = BMCLUrl; break; case DownloadSource.MCBBS: Source = MCBBSUrl; break; } Source += $"maven/net/minecraftforge/forge/{mc.ID}-{forge.Version}" + $"/forge-{mc.ID}-{forge.Version}-installer.jar"; DownloadTask dt = new(App.GetResourceString("String.NewDownloadTaskWindow.Core.Forge"), Source, local); dt.Todo = new Func <ProgressCallback, CancellationToken, Exception>((callback, cancelToken) => { try { IInstaller installer = new ForgeInstaller(local, new CommonInstallOptions() { GameRootPath = App.Handler.GameRootPath, IsClient = true, DownloadSource = App.Config.MainConfig.Download.DownloadSource, Java = App.Handler.Java }); installer.BeginInstall(callback, cancelToken).Wait(); return(null); } catch (Exception ex) { return(ex); } }); return(dt); }
public static async Task <bool> IsLostAssetsAsync(DownloadSource source, LaunchHandler core, MCVersion ver) { string assetsPath = core.GetAssetsIndexPath(ver.Assets); if (!File.Exists(assetsPath)) { return(true); } else { var assets = await core.GetAssetsAsync(ver); return(await Task.Factory.StartNew(() => { return IsLostAnyAssetsFromJassets(core, assets); })); } }
public static async Task WriteScripts(Config cfg, TransformedTarget[] tv, MCDownload downloader) { foreach (var t in tv) { MCVersion v = downloader.GetRemoteVersion(t.VersionID); VersionManifest vm = await v.GetManifest(); GameArguments combined = new GameArguments(t.From.JVMArguments) + vm.JavaArguments // (vm.LoggingSettings.ContainsKey("client") ? vm.LoggingSettings["client"].GameArgument : new GameArguments("")) + + new GameArguments("me.basiqueevangelist.launchergenerator.authhelper.MinecraftAuthHelper") + new GameArguments(vm.MainClass) + new GameArguments(cfg.Username) + new GameArguments(t.From.NewGameArguments) + vm.MinecraftArguments; AssetGroupIndex ai = await vm.AssetGroup.GetIndex(); Dictionary <string, string> variables = new Dictionary <string, string> { ["auth_player_name"] = "@USERNAME", ["version_name"] = t.VersionID, ["game_directory"] = ".", ["assets_root"] = "../../assets", ["game_assets"] = "../../assets" + (ai.IsVirtual ? "/virtual/" + vm.AssetGroup.ID : ""), ["assets_index_name"] = vm.AssetGroup.ID, ["auth_uuid"] = "@UUID", ["auth_access_token"] = "@ACCESSTOKEN", ["user_type"] = "mojang", ["version_type"] = v.Type.ToString(), ["classpath"] = Classpath(vm), ["natives_directory"] = "../../versions/" + t.VersionID + "/natives", ["launcher_name"] = "LauncherGenerator", ["launcher_version"] = "0.1a", ["path"] = vm.LoggingSettings.ContainsKey("client") ? "../../assets/log_configs/" + ((RemoteFile)vm.LoggingSettings["client"].File).Name : "" }; string[] cargs = combined.Process(variables, Array.Empty <string>()); string fname = "data/" + t.From.Name + (Environment.OSVersion.Platform == PlatformID.Win32NT ? ".bat" : ".sh"); using (FileStream fs = File.Open(fname, System.IO.FileMode.Create, FileAccess.Write, FileShare.Read)) using (StreamWriter sw = new StreamWriter(fs)) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { sw.WriteLine("title Minecraft " + t.VersionID + " launch script"); sw.WriteLine("cd %~dp0"); } else { sw.WriteLine("#!/bin/sh"); sw.WriteLine("printf \"\\033]0;Minecraft " + t.VersionID + " launch script\\007\""); sw.WriteLine("cd $(cd `dirname $0` && pwd)"); } sw.WriteLine("cd profiles/" + t.From.Profile); sw.WriteLine(t.From.JavaPath.Replace("\\", "\\\\") + " " + GameArguments.FoldArgs(cargs)); // sw.WriteLine("pause"); } Log.FileNew(fname); if (Environment.OSVersion.Platform != PlatformID.Win32NT) { UnixFileInfo ufi = new UnixFileInfo(fname); ufi.FileAccessPermissions |= FileAccessPermissions.UserExecute | FileAccessPermissions.GroupRead | FileAccessPermissions.OtherExecute; } } var assembly = typeof(Program).Assembly; using (Stream jarIn = assembly.GetManifestResourceStream("LauncherGenerator.MCAuthHelper.jar") ?? throw new NotImplementedException()) using (FileStream jarOut = File.Open("data/MCAuthHelper.jar", FileMode.Create, FileAccess.Write, FileShare.Delete)) await jarIn.CopyToAsync(jarOut); }
/// <summary> /// 获取版本丢失的库文件 /// </summary> /// <param name="core">所使用的启动核心</param> /// <param name="version">要检查的版本</param> /// <returns>返回Key为路径,value为库实例的集合</returns> public static Dictionary <string, Modules.Library> GetLostLibs(LaunchHandler core, MCVersion version) { Dictionary <string, Modules.Library> lostLibs = new Dictionary <string, Modules.Library>(); foreach (var item in version.Libraries) { string path = core.GetLibraryPath(item); if (lostLibs.ContainsKey(path)) { continue; } else if (!File.Exists(path)) { lostLibs.Add(path, item); } } return(lostLibs); }
public string GetGameVersionRootDir(MCVersion ver) { return(PathManager.GetGameVersionRootDir(VersionIsolation, GameRootPath, ver)); }
/// <summary> /// 获取丢失的资源文件下载任务 /// </summary> /// <param name="source"></param> /// <param name="core"></param> /// <param name="version"></param> /// <returns></returns> public async static Task <List <DownloadTask> > GetLostAssetsDownloadTaskAsync(DownloadSource source, LaunchHandler core, MCVersion ver) { List <DownloadTask> tasks = new List <DownloadTask>(); JAssets assets = null; string assetsPath = core.GetAssetsIndexPath(ver.Assets); if (!File.Exists(assetsPath)) { if (ver.AssetIndex != null) { string jsonUrl = GetDownloadUrl.DoURLReplace(source, ver.AssetIndex.URL); string assetsJson = await HttpRequesterAPI.HttpGetStringAsync(jsonUrl); assets = core.GetAssetsByJson(assetsJson); tasks.Add(new DownloadTask("资源文件引导", jsonUrl, assetsPath)); } else { return(tasks); } } else { assets = core.GetAssets(ver); } var lostAssets = GetLostAssets(core, assets); foreach (var item in lostAssets) { DownloadTask task = GetDownloadUrl.GetAssetsDownloadTask(source, item.Value, core); tasks.Add(task); } return(tasks); }
public JAssets GetAssets(MCVersion version) { return(assetsReader.GetAssets(version)); }