Beispiel #1
0
 public async Task <JAssets> GetAssetsAsync(Modules.Version version)
 {
     return(await Task.Factory.StartNew(() =>
     {
         return assetsReader.GetAssets(version);
     }));
 }
Beispiel #2
0
 static void LaunchGame(Version launchVer)
 {
     Console.WriteLine("Ready to launch version {0}", launchVer.ID);
     OfflineAuthenticator authenticator = new OfflineAuthenticator("Nsiso");
     var launchResult = handler.LaunchAsync(new LaunchSetting()
     {
         Version            = launchVer,
         AuthenticateResult = authenticator.DoAuthenticate()
     }).Result;
 }
Beispiel #3
0
 /// <summary>
 /// 获取版本是否丢失任何库文件
 /// </summary>
 /// <param name="core">启动核心</param>
 /// <param name="version">检查的版本</param>
 /// <returns>是否丢失任何库文件</returns>
 public static bool IsLostAnyLibs(LaunchHandler core, Version version)
 {
     foreach (var item in version.Libraries)
     {
         string path = core.GetLibraryPath(item);
         if (!File.Exists(path))
         {
             return(true);
         }
     }
     return(false);
 }
Beispiel #4
0
 public static bool IsLostJarCore(LaunchHandler core, Version version)
 {
     if (version.InheritsVersion == null)
     {
         string jarPath = core.GetJarPath(version);
         return(!File.Exists(jarPath));
     }
     else
     {
         return(false);
     }
 }
Beispiel #5
0
        //作者觉得使用这个方法判断是否丢失文件不如直接根据GetLostDependDownloadTask方法返回的列表的Count数来判断
        //毕竟这种方法大部分用在启动前判断是否丢失文件,但是如果丢失还是要获取一次列表,效率并没怎样优化
        //public static bool IsLostAnyDependent(LaunchHandler core, Version version)
        //{
        //    return IsLostJarCore(core, version) || IsLostAnyLibs(core, version) || IsLostAnyNatives(core, version);
        //}

        /// <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, Version version)
        {
            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 APIRequester.HttpGetStringAsync(GetDownloadUrl.GetCoreJsonDownloadURL(source, version.InheritsVersion));

                    string jsonFolder = Path.GetDirectoryName(innerJsonPath);
                    if (!Directory.Exists(jsonFolder))
                    {
                        Directory.CreateDirectory(jsonFolder);
                    }
                    File.WriteAllText(innerJsonPath, innerJsonStr);
                }
                else
                {
                    innerJsonStr = File.ReadAllText(innerJsonPath);
                }
                Version innerVer = core.JsonToVersion(innerJsonStr);
                if (innerVer != null)
                {
                    tasks.AddRange(await GetLostDependDownloadTaskAsync(source, core, innerVer));
                }
            }
            foreach (var item in lostLibs)
            {
                tasks.Add(GetDownloadUrl.GetLibDownloadTask(source, item));
            }
            foreach (var item in lostNatives)
            {
                tasks.Add(GetDownloadUrl.GetNativeDownloadTask(source, item));
            }
            return(tasks);
        }
        private string GetClassPaths(List <Modules.Library> libs, Modules.Version ver)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append('\"');

            foreach (var item in libs)
            {
                string libPath = handler.GetLibraryPath(item);
                stringBuilder.AppendFormat("{0};", libPath);
            }
            stringBuilder.Append(handler.GetJarPath(ver));
            stringBuilder.Append('\"');
            return(stringBuilder.ToString().Trim());
        }
Beispiel #7
0
        /// <summary>
        /// 获取版本丢失的natives文件
        /// </summary>
        /// <param name="core">所使用的核心</param>
        /// <param name="version">要检查的版本</param>
        /// <returns>返回Key为路径,value为native实例的集合</returns>
        public static Dictionary <string, Native> GetLostNatives(LaunchHandler core, Version 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);
        }
Beispiel #8
0
        private async Task AppendForgeDownloadTask(Version ver, JWForge forge)
        {
            try
            {
                //string json = await APIRequester.HttpGetStringAsync(apiHandler.DoURLReplace(item.Url));
                //Version ver = App.handler.JsonToVersion(json);
                //string jsonPath = App.handler.GetJsonPath(ver.ID);

                //string dir = Path.GetDirectoryName(jsonPath);
                //if (!Directory.Exists(dir))
                //{
                //    Directory.CreateDirectory(dir);
                //}

                //File.WriteAllText(jsonPath, json);

                //List<DownloadTask> tasks = new List<DownloadTask>();

                //tasks.Add(new DownloadTask("资源引导", apiHandler.DoURLReplace(ver.AssetIndex.URL), App.handler.GetAssetsIndexPath(ver.Assets)));

                //tasks.AddRange(await NsisoLauncherCore.Util.FileHelper.GetLostDependDownloadTaskAsync(App.config.MainConfig.Download.DownloadSource, App.handler, ver));

                //App.downloader.SetDownloadTasks(tasks);
                //App.downloader.StartDownload();
            }
            catch (WebException ex)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    this.ShowMessageAsync("获取版本信息失败", "请检查您的网络是否正常或更改下载源/n原因:" + ex.Message);
                }));
            }
            catch (Exception ex)
            {
                AggregateExceptionArgs args = new AggregateExceptionArgs()
                {
                    AggregateException = new AggregateException(ex)
                };
                App.CatchAggregateException(this, args);
            }
        }
Beispiel #9
0
        private async void RefreshLiteloader()
        {
            Version ver = null;

            if (verToInstallLiteComboBox.SelectedItem != null)
            {
                ver = (Version)verToInstallLiteComboBox.SelectedItem;
            }
            else
            {
                await this.ShowMessageAsync("您未选择要安装Liteloader的版本", "您需要选择一个需要安装Liteloader的Minecraft本体");

                return;
            }
            var loading = await this.ShowProgressAsync("获取Liteloader列表中", "请稍后");

            loading.SetIndeterminate();
            List <JWLiteloader> result = new List <JWLiteloader>();

            try
            {
                result.Add(await apiHandler.GetLiteloaderList(ver));
            }
            catch (WebException)
            {
                result = null;
            }
            await loading.CloseAsync();

            if (result == null)
            {
                await this.ShowMessageAsync("获取Liteloader列表失败", "请检查您的网络是否正常或更改下载源");
            }
            else
            {
                liteloaderListDataGrid.ItemsSource = result;
            }
        }
Beispiel #10
0
        private async void DownloadForgeButton_Click(object sender, RoutedEventArgs e)
        {
            Version ver = null;

            if (verToInstallForgeComboBox.SelectedItem != null)
            {
                ver = (Version)verToInstallForgeComboBox.SelectedItem;
            }
            else
            {
                await this.ShowMessageAsync("您未选择要安装Forge的Minecraft", "您需要选择一个需要安装Forge的Minecraft本体");

                return;
            }

            JWForge forge = null;

            if (forgeListDataGrid.SelectedItem != null)
            {
                forge = (JWForge)forgeListDataGrid.SelectedItem;
            }
            else
            {
                await this.ShowMessageAsync("您未选择要安装的Forge", "您需要选择一个要安装Forge");

                return;
            }

            var loading = await this.ShowProgressAsync("准备进行下载", string.Format("即将为版本{0}下载安装Forge:{1}", ver.ID, forge.Version));

            loading.SetIndeterminate();
            //await AppendVersionsDownloadTask(selectItems);
            await loading.CloseAsync();

            this.Close();
        }
        public Modules.Version JsonToVersion(JObject obj)
        {
            Modules.Version ver = new Modules.Version();
            ver = obj.ToObject <Modules.Version>();
            JObject innerVer = null;

            if (ver.InheritsVersion != null)
            {
                SendDebugLog(string.Format("检测到\"{0}\"继承于\"{1}\"", ver.ID, ver.InheritsVersion));
                string innerJsonStr = GetVersionJsonText(ver.InheritsVersion);
                if (innerJsonStr != null)
                {
                    innerVer = JObject.Parse(innerJsonStr);
                }
            }
            if (obj.ContainsKey("arguments"))
            {
                #region 处理新版本引导

                SendDebugLog(string.Format("检测到\"{0}\"使用新版本启动参数", ver.ID));

                #region 处理版本继承
                if (innerVer != null && innerVer.ContainsKey("arguments"))
                {
                    JObject innerVerArg = (JObject)innerVer["arguments"];
                    if (innerVerArg.ContainsKey("game"))
                    {
                        ver.MinecraftArguments += string.Format("{0} ", ParseGameArgFromJson(innerVerArg["game"]));
                    }
                    if (innerVerArg.ContainsKey("jvm"))
                    {
                        ver.JvmArguments += string.Format("{0} ", ParseJvmArgFromJson(innerVerArg["jvm"]));
                    }
                }
                #endregion

                JObject verArg = (JObject)obj["arguments"];

                #region 游戏参数
                if (verArg.ContainsKey("game"))
                {
                    JToken gameArg = verArg["game"];
                    ver.MinecraftArguments += ParseGameArgFromJson(gameArg);
                }
                #endregion

                #region JVM参数
                if (verArg.ContainsKey("jvm"))
                {
                    JToken jvmArg = verArg["jvm"];
                    ver.JvmArguments += ParseJvmArgFromJson(jvmArg);
                }
                #endregion
            }
            #endregion
            else
            {
                #region 旧版本添加默认JVM参数
                SendDebugLog(string.Format("检测到\"{0}\"使用旧版本启动参数", ver.ID));
                ver.JvmArguments = "-Djava.library.path=${natives_directory} -cp ${classpath}";
                #endregion
            }

            #region 处理依赖
            ver.Libraries = new List <Library>();
            ver.Natives   = new List <Native>();
            var libToken = obj["libraries"];
            foreach (JToken lib in libToken)
            {
                var libObj = lib.ToObject <JLibrary>();

                if (CheckAllowed(libObj.Rules))
                {
                    var parts = libObj.Name.Split(':');

                    string package = parts[0];
                    string name    = parts[1];
                    string version = parts[2];

                    if (libObj.Natives == null)
                    {
                        //不为native
                        Library library = new Library()
                        {
                            Package = package,
                            Name    = name,
                            Version = version
                        };
                        if (!string.IsNullOrWhiteSpace(libObj.Url))
                        {
                            library.Url = libObj.Url;
                        }
                        if (libObj.Downloads?.Artifact != null)
                        {
                            library.LibDownloadInfo = libObj.Downloads.Artifact;
                        }
                        ver.Libraries.Add(library);
                    }
                    else
                    {
                        //为native
                        var native = new Native()
                        {
                            Package      = package,
                            Name         = name,
                            Version      = version,
                            NativeSuffix = libObj.Natives["windows"].Replace("${arch}", SystemTools.GetSystemArch() == ArchEnum.x64 ? "64" : "32")
                        };
                        if (libObj.Extract != null)
                        {
                            native.Exclude = libObj.Extract.Exculde;
                        }
                        if (libObj.Downloads?.Artifact != null)
                        {
                            native.LibDownloadInfo = libObj.Downloads.Artifact;
                        }
                        if (libObj.Downloads?.Classifiers?.Natives != null)
                        {
                            native.NativeDownloadInfo = libObj.Downloads.Classifiers.Natives;
                        }
                        ver.Natives.Add(native);
                    }
                }
            }
            #endregion

            #region 处理版本继承
            if (innerVer != null)
            {
                var iv = JsonToVersion(innerVer);
                if (iv != null)
                {
                    ver.Assets     = iv.Assets;
                    ver.AssetIndex = iv.AssetIndex;
                    ver.Natives.AddRange(iv.Natives);
                    ver.Libraries.AddRange(iv.Libraries);
                    ver.Jar = iv.ID;
                }
            }
            #endregion

            return(ver);
        }
Beispiel #12
0
 public string GetVersionOptionsPath(Modules.Version version)
 {
     return(PathManager.GetVersionOptionsPath(VersionIsolation, GameRootPath, version));
 }
Beispiel #13
0
 public JAssets GetAssets(Modules.Version version)
 {
     return(assetsReader.GetAssets(version));
 }
Beispiel #14
0
 public string GetGameVersionRootDir(Modules.Version ver)
 {
     return(PathManager.GetGameVersionRootDir(VersionIsolation, GameRootPath, ver));
 }
Beispiel #15
0
 public string GetJarPath(Modules.Version ver)
 {
     return(PathManager.GetJarPath(GameRootPath, ver));
 }
Beispiel #16
0
 public Modules.Version RefreshVersion(Modules.Version ver)
 {
     return(versionReader.GetVersion(ver.ID));
 }
Beispiel #17
0
        public static async Task <bool> IsLostAssetsAsync(DownloadSource source, LaunchHandler core, Version ver)
        {
            string assetsPath = core.GetAssetsIndexPath(ver.Assets);

            if (!File.Exists(assetsPath))
            {
                return(ver.AssetIndex != null);
            }
            else
            {
                var assets = await core.GetAssetsAsync(ver);

                return(await Task.Factory.StartNew(() =>
                {
                    return IsLostAnyAssetsFromJassets(core, assets);
                }));
            }
        }
Beispiel #18
0
        /// <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, Version 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 APIRequester.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);
                if (!tasks.Contains(task))
                {
                    tasks.Add(task);
                }
            }
            return(tasks);
        }
Beispiel #19
0
        /// <summary>
        /// 获取版本丢失的库文件
        /// </summary>
        /// <param name="core">所使用的启动核心</param>
        /// <param name="version">要检查的版本</param>
        /// <returns>返回Key为路径,value为库实例的集合</returns>
        public static Dictionary <string, Modules.Library> GetLostLibs(LaunchHandler core, Version 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);
        }
Beispiel #20
0
        private async Task LaunchGameFromWindow()
        {
            try
            {
                string userName = playerNameTextBox.Text;

                #region 检查有效数据
                if (authTypeCombobox.SelectedItem == null)
                {
                    await this.ShowMessageAsync(App.GetResourceString("String.Message.EmptyAuthType"),
                                                App.GetResourceString("String.Message.EmptyAuthType2"));

                    return;
                }
                if (string.IsNullOrWhiteSpace(userName))
                {
                    await this.ShowMessageAsync(App.GetResourceString("String.Message.EmptyUsername"),
                                                App.GetResourceString("String.Message.EmptyUsername2"));

                    return;
                }
                if (launchVersionCombobox.SelectedItem == null)
                {
                    await this.ShowMessageAsync(App.GetResourceString("String.Message.EmptyLaunchVersion"),
                                                App.GetResourceString("String.Message.EmptyLaunchVersion2"));

                    return;
                }
                if (App.handler.Java == null)
                {
                    await this.ShowMessageAsync(App.GetResourceString("String.Message.NoJava"), App.GetResourceString("String.Message.NoJava2"));

                    return;
                }
                #endregion

                NsisoLauncherCore.Modules.Version launchVersion = (NsisoLauncherCore.Modules.Version)launchVersionCombobox.SelectedItem;
                AuthTypeItem auth = (AuthTypeItem)authTypeCombobox.SelectedItem;

                #region 保存启动数据
                App.config.MainConfig.History.LastLaunchVersion = launchVersion.ID;
                App.config.MainConfig.User.UserName             = userName;
                #endregion

                LaunchSetting launchSetting = new LaunchSetting()
                {
                    Version = (NsisoLauncherCore.Modules.Version)launchVersionCombobox.SelectedItem
                };

                this.loadingGrid.Visibility = Visibility.Visible;
                this.loadingRing.IsActive   = true;

                #region 验证

                #region 设置ClientToken
                if (string.IsNullOrWhiteSpace(App.config.MainConfig.User.ClientToken))
                {
                    App.config.MainConfig.User.ClientToken = Guid.NewGuid().ToString("N");
                }
                else
                {
                    Requester.ClientToken = App.config.MainConfig.User.ClientToken;
                }
                #endregion

                #region 多语言支持变量(old)
                //string autoVerifyingMsg = null;
                //string autoVerifyingMsg2 = null;
                //string autoVerificationFailedMsg = null;
                //string autoVerificationFailedMsg2 = null;
                //string loginMsg = null;
                //string loginMsg2 = null;
                LoginDialogSettings loginDialogSettings = new LoginDialogSettings()
                {
                    NegativeButtonText         = App.GetResourceString("String.Base.Cancel"),
                    AffirmativeButtonText      = App.GetResourceString("String.Base.Login"),
                    RememberCheckBoxText       = App.GetResourceString("String.Base.ShouldRememberLogin"),
                    UsernameWatermark          = App.GetResourceString("String.Base.Username"),
                    InitialUsername            = userName,
                    RememberCheckBoxVisibility = Visibility,
                    EnablePasswordPreview      = true,
                    PasswordWatermark          = App.GetResourceString("String.Base.Password"),
                    NegativeButtonVisibility   = Visibility.Visible
                };
                //string verifyingMsg = null, verifyingMsg2 = null, verifyingFailedMsg = null, verifyingFailedMsg2 = null;
                #endregion

                //主验证器接口
                IAuthenticator authenticator  = null;
                bool           shouldRemember = false;

                bool isSameAuthType = App.config.MainConfig.User.AuthenticationType == auth.Type;
                bool isRemember     = (!string.IsNullOrWhiteSpace(App.config.MainConfig.User.AccessToken)) && (App.config.MainConfig.User.AuthenticationUUID != null);

                switch (auth.Type)
                {
                    #region 离线验证
                case Config.AuthenticationType.OFFLINE:
                    authenticator = new OfflineAuthenticator(userName);
                    break;
                    #endregion

                    #region Mojang验证
                case Config.AuthenticationType.MOJANG:
                    if (isSameAuthType && isRemember)
                    {
                        var mYggTokenAuthenticator = new YggdrasilTokenAuthenticator(App.config.MainConfig.User.AccessToken,
                                                                                     App.config.MainConfig.User.AuthenticationUUID,
                                                                                     App.config.MainConfig.User.AuthenticationUserData);
                        mYggTokenAuthenticator.ProxyAuthServerAddress = "https://authserver.mojang.com";
                        authenticator = mYggTokenAuthenticator;
                    }
                    else
                    {
                        var mojangLoginDResult = await this.ShowLoginAsync(App.GetResourceString("String.Mainwindow.Auth.Mojang.Login"),
                                                                           App.GetResourceString("String.Mainwindow.Auth.Mojang.Login2"),
                                                                           loginDialogSettings);

                        if (IsValidateLoginData(mojangLoginDResult))
                        {
                            var mYggAuthenticator = new YggdrasilAuthenticator(new Credentials()
                            {
                                Username = mojangLoginDResult.Username,
                                Password = mojangLoginDResult.Password
                            });
                            mYggAuthenticator.ProxyAuthServerAddress = "https://authserver.mojang.com";
                            authenticator  = mYggAuthenticator;
                            shouldRemember = mojangLoginDResult.ShouldRemember;
                        }
                        else
                        {
                            await this.ShowMessageAsync("您输入的账号或密码为空", "请检查您是否正确填写登陆信息");

                            return;
                        }
                    }
                    break;
                    #endregion

                    #region 统一通行证验证
                case Config.AuthenticationType.NIDE8:
                    if (App.nide8Handler == null)
                    {
                        await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.Auth.Nide8.NoID"),
                                                    App.GetResourceString("String.Mainwindow.Auth.Nide8.NoID2"));

                        return;
                    }
                    var nide8ChooseResult = await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.Auth.Nide8.Login2"), App.GetResourceString("String.Base.Choose"),
                                                                        MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary,
                                                                        new MetroDialogSettings()
                    {
                        AffirmativeButtonText    = App.GetResourceString("String.Base.Login"),
                        NegativeButtonText       = App.GetResourceString("String.Base.Cancel"),
                        FirstAuxiliaryButtonText = App.GetResourceString("String.Base.Register"),
                        DefaultButtonFocus       = MessageDialogResult.Affirmative
                    });

                    switch (nide8ChooseResult)
                    {
                    case MessageDialogResult.Canceled:
                        return;

                    case MessageDialogResult.Negative:
                        return;

                    case MessageDialogResult.FirstAuxiliary:
                        System.Diagnostics.Process.Start(string.Format("https://login2.nide8.com:233/{0}/register", App.nide8Handler.ServerID));
                        return;

                    case MessageDialogResult.SecondAuxiliary:
                        if (isSameAuthType && isRemember)
                        {
                            var nYggTokenCator = new Nide8TokenAuthenticator(App.config.MainConfig.User.AccessToken,
                                                                             App.config.MainConfig.User.AuthenticationUUID,
                                                                             App.config.MainConfig.User.AuthenticationUserData);
                            nYggTokenCator.ProxyAuthServerAddress = string.Format("{0}authserver", App.nide8Handler.BaseURL);
                            authenticator = nYggTokenCator;
                        }
                        else
                        {
                            var nide8LoginDResult = await this.ShowLoginAsync(App.GetResourceString("String.Mainwindow.Auth.Nide8.Login"),
                                                                              App.GetResourceString("String.Mainwindow.Auth.Nide8.Login2"),
                                                                              loginDialogSettings);

                            if (IsValidateLoginData(nide8LoginDResult))
                            {
                                var nYggCator = new Nide8Authenticator(new Credentials()
                                {
                                    Username = nide8LoginDResult.Username,
                                    Password = nide8LoginDResult.Password
                                });
                                nYggCator.ProxyAuthServerAddress = string.Format("{0}authserver", App.nide8Handler.BaseURL);
                                authenticator  = nYggCator;
                                shouldRemember = nide8LoginDResult.ShouldRemember;
                            }
                            else
                            {
                                await this.ShowMessageAsync("您输入的账号或密码为空", "请检查您是否正确填写登陆信息");

                                return;
                            }
                        }
                        break;

                    default:
                        break;
                    }
                    break;
                    #endregion

                    #region 自定义验证
                case Config.AuthenticationType.CUSTOM_SERVER:
                    string customAuthServer = App.config.MainConfig.User.AuthServer;
                    if (string.IsNullOrWhiteSpace(customAuthServer))
                    {
                        await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.Auth.Custom.NoAdrress"),
                                                    App.GetResourceString("String.Mainwindow.Auth.Custom.NoAdrress2"));

                        return;
                    }
                    else
                    {
                        if (shouldRemember && isSameAuthType)
                        {
                            var cYggTokenCator = new YggdrasilTokenAuthenticator(App.config.MainConfig.User.AccessToken,
                                                                                 App.config.MainConfig.User.AuthenticationUUID,
                                                                                 App.config.MainConfig.User.AuthenticationUserData);
                            cYggTokenCator.ProxyAuthServerAddress = customAuthServer;
                        }
                        else
                        {
                            var customLoginDResult = await this.ShowLoginAsync(App.GetResourceString("String.Mainwindow.Auth.Custom.Login"),
                                                                               App.GetResourceString("String.Mainwindow.Auth.Custom.Login2"),
                                                                               loginDialogSettings);

                            if (IsValidateLoginData(customLoginDResult))
                            {
                                var cYggAuthenticator = new YggdrasilAuthenticator(new Credentials()
                                {
                                    Username = customLoginDResult.Username,
                                    Password = customLoginDResult.Password
                                });
                                cYggAuthenticator.ProxyAuthServerAddress = customAuthServer;
                                authenticator  = cYggAuthenticator;
                                shouldRemember = customLoginDResult.ShouldRemember;
                            }
                            else
                            {
                                await this.ShowMessageAsync("您输入的账号或密码为空", "请检查您是否正确填写登陆信息");

                                return;
                            }
                        }
                    }
                    break;
                    #endregion

                default:
                    authenticator = new OfflineAuthenticator(userName);
                    break;
                }

                #region Old
                //if (auth.Type != Config.AuthenticationType.OFFLINE)
                //{
                //    try
                //    {
                //        #region 如果记住登陆(有登陆记录)
                //        if ((!string.IsNullOrWhiteSpace(App.config.MainConfig.User.AccessToken)) && (App.config.MainConfig.User.AuthenticationUUID != null))
                //        {
                //            authenticator = new YggdrasilTokenAuthenticator(App.config.MainConfig.User.AccessToken,
                //                App.config.MainConfig.User.AuthenticationUUID,
                //                App.config.MainConfig.User.AuthenticationUserData);
                //            //var loader = await this.ShowProgressAsync(autoVerifyingMsg, autoVerifyingMsg2);
                //            //loader.SetIndeterminate();
                //            //Validate validate = new Validate(App.config.MainConfig.User.AccessToken);
                //            //var validateResult = await validate.PerformRequestAsync();
                //            //if (validateResult.IsSuccess)
                //            //{

                //            //    launchSetting.AuthenticateAccessToken = App.config.MainConfig.User.AccessToken;
                //            //    launchSetting.AuthenticateUUID = App.config.MainConfig.User.AuthenticationUUID;
                //            //    await loader.CloseAsync();
                //            //}
                //            //else
                //            //{
                //            //    Refresh refresher = new Refresh(App.config.MainConfig.User.AccessToken);
                //            //    var refreshResult = await refresher.PerformRequestAsync();
                //            //    await loader.CloseAsync();
                //            //    if (refreshResult.IsSuccess)
                //            //    {
                //            //        App.config.MainConfig.User.AccessToken = refreshResult.AccessToken;

                //            //        launchSetting.AuthenticateUUID = App.config.MainConfig.User.AuthenticationUUID;
                //            //        launchSetting.AuthenticateAccessToken = refreshResult.AccessToken;
                //            //    }
                //            //    else
                //            //    {
                //            //        App.config.MainConfig.User.AccessToken = string.Empty;
                //            //        App.config.Save();
                //            //        await this.ShowMessageAsync(autoVerificationFailedMsg, autoVerificationFailedMsg2);
                //            //        return;
                //            //    }
                //            //}
                //        }
                //        #endregion

                //        #region 从零登陆
                //        else
                //        {
                //            var loginMsgResult = await this.ShowLoginAsync(loginMsg, loginMsg2, loginDialogSettings);

                //            if (loginMsgResult == null)
                //            {
                //                return;
                //            }
                //            var loader = await this.ShowProgressAsync(verifyingMsg, verifyingMsg2);
                //            loader.SetIndeterminate();
                //            userName = loginMsgResult.Username;
                //            Authenticate authenticate = new Authenticate(new Credentials() { Username = loginMsgResult.Username, Password = loginMsgResult.Password });
                //            var aloginResult = await authenticate.PerformRequestAsync();
                //            await loader.CloseAsync();
                //            if (aloginResult.IsSuccess)
                //            {
                //                if (loginMsgResult.ShouldRemember)
                //                {
                //                    App.config.MainConfig.User.AccessToken = aloginResult.AccessToken;
                //                }
                //                App.config.MainConfig.User.AuthenticationUserData = aloginResult.User;
                //                App.config.MainConfig.User.AuthenticationUUID = aloginResult.SelectedProfile;

                //                launchSetting.AuthenticateAccessToken = aloginResult.AccessToken;
                //                launchSetting.AuthenticateUUID = aloginResult.SelectedProfile;
                //                launchSetting.AuthenticationUserData = aloginResult.User;
                //            }
                //            else
                //            {
                //                await this.ShowMessageAsync(verifyingFailedMsg, verifyingFailedMsg2 + aloginResult.Error.ErrorMessage);
                //                return;
                //            }
                //        }
                //        #endregion
                //    }
                //    catch (Exception ex)
                //    {
                //        await this.ShowMessageAsync(verifyingFailedMsg, verifyingFailedMsg2 + ex.Message);
                //        return;
                //    }
                //}
                #endregion

                if (auth.Type != Config.AuthenticationType.OFFLINE)
                {
                    string currentLoginType = string.Format("正在进行{0}中...", auth.Name);
                    string loginMsg         = "这需要联网进行操作,可能需要一分钟的时间";
                    var    loader           = await this.ShowProgressAsync(currentLoginType, loginMsg);

                    loader.SetIndeterminate();
                    var authResult = await authenticator.DoAuthenticateAsync();

                    await loader.CloseAsync();

                    switch (authResult.State)
                    {
                    case AuthState.SUCCESS:
                        if (shouldRemember)
                        {
                            App.config.MainConfig.User.AccessToken            = authResult.AccessToken;
                            App.config.MainConfig.User.AuthenticationUUID     = authResult.UUID;
                            App.config.MainConfig.User.AuthenticationUserData = authResult.UserData;
                        }
                        launchSetting.AuthenticateResult = authResult;
                        break;

                    case AuthState.REQ_LOGIN:
                        await this.ShowMessageAsync("验证失败:您的登陆信息已过期",
                                                    string.Format("请您重新进行登陆。具体信息:{0}", authResult.Error.ErrorMessage));

                        return;

                    case AuthState.ERR_INVALID_CRDL:
                        await this.ShowMessageAsync("验证失败:您的登陆账号或密码错误",
                                                    string.Format("请您确认您输入的账号密码正确。具体信息:{0}", authResult.Error.ErrorMessage));

                        return;

                    case AuthState.ERR_NOTFOUND:
                        await this.ShowMessageAsync("验证失败:您的账号未找到",
                                                    string.Format("请确认您的账号和游戏角色存在。具体信息:{0}", authResult.Error.ErrorMessage));

                        return;

                    case AuthState.ERR_OTHER:
                        await this.ShowMessageAsync("验证失败:其他错误",
                                                    string.Format("具体信息:{0}", authResult.Error.ErrorMessage));

                        return;

                    case AuthState.ERR_INSIDE:
                        await this.ShowMessageAsync("验证失败:启动器内部错误",
                                                    string.Format("建议您联系启动器开发者进行解决。具体信息:{0}", authResult.Error.ErrorMessage));

                        return;

                    default:
                        await this.ShowMessageAsync("验证失败:未知错误",
                                                    "建议您联系启动器开发者进行解决。");

                        return;
                    }
                }
                else
                {
                    launchSetting.AuthenticateResult = await authenticator.DoAuthenticateAsync();
                }
                App.config.MainConfig.User.AuthenticationType = auth.Type;
                #endregion

                #region 检查游戏完整
                List <DownloadTask> losts = new List <DownloadTask>();

                App.logHandler.AppendInfo("检查丢失的依赖库文件中...");
                var lostDepend = await FileHelper.GetLostDependDownloadTaskAsync(
                    App.config.MainConfig.Download.DownloadSource,
                    App.handler,
                    launchSetting.Version);

                if (auth.Type == Config.AuthenticationType.NIDE8)
                {
                    string nideJarPath = App.handler.GetNide8JarPath();
                    if (!File.Exists(nideJarPath))
                    {
                        lostDepend.Add(new DownloadTask("统一通行证核心", "https://login2.nide8.com:233/index/jar", nideJarPath));
                    }
                }
                if (App.config.MainConfig.Environment.DownloadLostDepend && lostDepend.Count != 0)
                {
                    MessageDialogResult downDependResult = await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.NeedDownloadDepend"),
                                                                                       App.GetResourceString("String.Mainwindow.NeedDownloadDepend2"),
                                                                                       MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, new MetroDialogSettings()
                    {
                        AffirmativeButtonText    = App.GetResourceString("String.Base.Download"),
                        NegativeButtonText       = App.GetResourceString("String.Base.Cancel"),
                        FirstAuxiliaryButtonText = App.GetResourceString("String.Base.Unremember"),
                        DefaultButtonFocus       = MessageDialogResult.Affirmative
                    });

                    switch (downDependResult)
                    {
                    case MessageDialogResult.Affirmative:
                        losts.AddRange(lostDepend);
                        break;

                    case MessageDialogResult.FirstAuxiliary:
                        App.config.MainConfig.Environment.DownloadLostDepend = false;
                        break;

                    default:
                        break;
                    }
                }

                App.logHandler.AppendInfo("检查丢失的资源文件中...");
                if (App.config.MainConfig.Environment.DownloadLostAssets && (await FileHelper.IsLostAssetsAsync(App.config.MainConfig.Download.DownloadSource,
                                                                                                                App.handler, launchSetting.Version)))
                {
                    MessageDialogResult downDependResult = await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.NeedDownloadAssets"),
                                                                                       App.GetResourceString("String.Mainwindow.NeedDownloadAssets2"),
                                                                                       MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, new MetroDialogSettings()
                    {
                        AffirmativeButtonText    = App.GetResourceString("String.Base.Download"),
                        NegativeButtonText       = App.GetResourceString("String.Base.Cancel"),
                        FirstAuxiliaryButtonText = App.GetResourceString("String.Base.Unremember"),
                        DefaultButtonFocus       = MessageDialogResult.Affirmative
                    });

                    switch (downDependResult)
                    {
                    case MessageDialogResult.Affirmative:
                        var lostAssets = await FileHelper.GetLostAssetsDownloadTaskAsync(
                            App.config.MainConfig.Download.DownloadSource,
                            App.handler, launchSetting.Version);

                        losts.AddRange(lostAssets);
                        break;

                    case MessageDialogResult.FirstAuxiliary:
                        App.config.MainConfig.Environment.DownloadLostAssets = false;
                        break;

                    default:
                        break;
                    }
                }

                if (losts.Count != 0)
                {
                    App.downloader.SetDownloadTasks(losts);
                    App.downloader.StartDownload();
                    await new Windows.DownloadWindow().ShowWhenDownloading();
                }

                #endregion

                #region 根据配置文件设置
                launchSetting.AdvencedGameArguments += App.config.MainConfig.Environment.AdvencedGameArguments;
                launchSetting.AdvencedJvmArguments  += App.config.MainConfig.Environment.AdvencedJvmArguments;
                launchSetting.GCArgument            += App.config.MainConfig.Environment.GCArgument;
                launchSetting.GCEnabled              = App.config.MainConfig.Environment.GCEnabled;
                launchSetting.GCType     = App.config.MainConfig.Environment.GCType;
                launchSetting.JavaAgent += App.config.MainConfig.Environment.JavaAgent;
                if (auth.Type == Config.AuthenticationType.NIDE8)
                {
                    launchSetting.JavaAgent += string.Format(" \"{0}\"={1}", App.handler.GetNide8JarPath(), App.config.MainConfig.User.Nide8ServerID);
                }

                //直连服务器设置
                if ((auth.Type == Config.AuthenticationType.NIDE8) && App.config.MainConfig.User.AllUsingNide8)
                {
                    var nide8ReturnResult = await App.nide8Handler.GetInfoAsync();

                    if (App.config.MainConfig.User.AllUsingNide8 && !string.IsNullOrWhiteSpace(nide8ReturnResult.Meta.ServerIP))
                    {
                        Server   server   = new Server();
                        string[] serverIp = nide8ReturnResult.Meta.ServerIP.Split(':');
                        if (serverIp.Length == 2)
                        {
                            server.Address = serverIp[0];
                            server.Port    = ushort.Parse(serverIp[1]);
                        }
                        else
                        {
                            server.Address = nide8ReturnResult.Meta.ServerIP;
                            server.Port    = 25565;
                        }
                        launchSetting.LaunchToServer = server;
                    }
                }
                else if (App.config.MainConfig.Server.LaunchToServer)
                {
                    launchSetting.LaunchToServer = new Server()
                    {
                        Address = App.config.MainConfig.Server.Address, Port = App.config.MainConfig.Server.Port
                    };
                }

                //自动内存设置
                if (App.config.MainConfig.Environment.AutoMemory)
                {
                    var m = SystemTools.GetBestMemory(App.handler.Java);
                    App.config.MainConfig.Environment.MaxMemory = m;
                    launchSetting.MaxMemory = m;
                }
                else
                {
                    launchSetting.MaxMemory = App.config.MainConfig.Environment.MaxMemory;
                }
                launchSetting.VersionType = App.config.MainConfig.Customize.VersionInfo;
                launchSetting.WindowSize  = App.config.MainConfig.Environment.WindowSize;
                #endregion

                #region 配置文件处理
                App.config.Save();
                #endregion

                #region 启动

                App.logHandler.OnLog += (a, b) => { this.Invoke(() => { launchInfoBlock.Text = b.Message; }); };
                var result = await App.handler.LaunchAsync(launchSetting);

                App.logHandler.OnLog -= (a, b) => { this.Invoke(() => { launchInfoBlock.Text = b.Message; }); };

                //程序猿是找不到女朋友的了 :)
                if (!result.IsSuccess)
                {
                    await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.LaunchError") + result.LaunchException.Title, result.LaunchException.Message);

                    App.logHandler.AppendError(result.LaunchException);
                }
                else
                {
                    try
                    {
                        await Task.Factory.StartNew(() =>
                        {
                            result.Process.WaitForInputIdle();
                        });
                    }
                    catch (Exception ex)
                    {
                        await this.ShowMessageAsync("启动后等待游戏窗口响应异常", "这可能是由于游戏进程发生意外(闪退)导致的。具体原因:" + ex.Message);

                        return;
                    }
                    if (App.config.MainConfig.Environment.ExitAfterLaunch)
                    {
                        Application.Current.Shutdown();
                    }
                    this.WindowState = WindowState.Minimized;
                    Refresh();

                    //自定义处理
                    if (!string.IsNullOrWhiteSpace(App.config.MainConfig.Customize.GameWindowTitle))
                    {
                        GameHelper.SetGameTitle(result, App.config.MainConfig.Customize.GameWindowTitle);
                    }
                    if (App.config.MainConfig.Customize.CustomBackGroundMusic)
                    {
                        mediaElement.Volume = 0.5;
                        await Task.Factory.StartNew(() =>
                        {
                            try
                            {
                                for (int i = 0; i < 50; i++)
                                {
                                    this.Dispatcher.Invoke(new Action(() =>
                                    {
                                        this.mediaElement.Volume -= 0.01;
                                    }));
                                    Thread.Sleep(50);
                                }
                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    this.mediaElement.Stop();
                                }));
                            }
                            catch (Exception) { }
                        });
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                App.logHandler.AppendFatal(ex);
            }
            finally
            {
                this.loadingGrid.Visibility = Visibility.Hidden;
                this.loadingRing.IsActive   = false;
            }
        }