Пример #1
0
        void TestStartSync(MSession session)
        {
            var path     = new MinecraftPath();
            var launcher = new CMLauncher(path);

            launcher.FileChanged     += Downloader_ChangeFile;
            launcher.ProgressChanged += Downloader_ChangeProgress;

            var versions = launcher.GetAllVersions();

            foreach (var item in versions)
            {
                Console.WriteLine(item.Name);
            }

            var process = launcher.CreateProcess("1.5.2", new MLaunchOption
            {
                Session = session
            });

            var processUtil = new CmlLib.Utils.ProcessUtil(process);

            processUtil.OutputReceived += (s, e) => Console.WriteLine(e);
            processUtil.StartWithEvents();
        }
Пример #2
0
        public static MVersionCollection LoadVersions()
        {
            var mcp      = new MinecraftPath(Path.Combine(Utility.GetWorkingDir(), ".minecraft"));
            var launcher = new CMLauncher(mcp);

            return(launcher.GetAllVersions());
        }
Пример #3
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            btnLogin.Enabled   = false;
            btnSignout.Enabled = false;
            btnStart.Enabled   = false;

            new Thread(() =>
            {
                try
                {
                    var path                  = new MinecraftPath();
                    var launcher              = new CMLauncher(path);
                    launcher.FileChanged     += Launcher_FileChanged;
                    launcher.ProgressChanged += Launcher_ProgressChanged;

                    var versions    = launcher.GetAllVersions();
                    var lastVersion = versions.LatestReleaseVersion;

                    var process = launcher.CreateProcess(lastVersion.Name, new MLaunchOption()
                    {
                        Session = this.session
                    });

                    process.Start();
                    MessageBox.Show("Success");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }).Start();
        }
Пример #4
0
        private void winactive(object sender, RoutedEventArgs e)
        {
            var th = new Thread(new ThreadStart(delegate
            {
                var McPath   = Minecraft.GetOSDefaultPath();
                var launcher = new CMLauncher(McPath);

                // you must write this because of cmllib.core bug. it will be fixed soon
                launcher.ProgressChanged += Launcher_ProgressChanged;
                launcher.FileChanged     += Launcher_FileChanged;

                launcher.UpdateProfiles();                 // this code will block ui, so it should run in thread

                Dispatcher.BeginInvoke(new Action(delegate // call UI Thread
                {
                    foreach (var item in launcher.Profiles)
                    {
                        if (item.MType == MProfileType.Release || item.MType == MProfileType.Custom)
                        {
                            LauncherProfiles.Items.Add(item.Name);
                        }
                    }
                }));
            }));

            th.Start();
        }
        public static async Task LaunchGameAsync(FileManager.Modpacks modpack)
        {
            try
            {
                var path     = new MinecraftPath(Directory.GetCurrentDirectory() + $@"\Launcher\{modpack}");
                var launcher = new CMLauncher(path);


                // more options : https://github.com/AlphaBs/CmlLib.Core/wiki/MLaunchOption
                var launchOption = new MLaunchOption
                {
                    MaximumRamMb = Settings.RAM,
                    Session      = SESSION
                };

                forgeVersion = File.ReadAllText($"Launcher/{modpack}/Forge Version.txt");
                var process = await launcher.CreateProcessAsync(forgeVersion, launchOption);

                process.Start();
            }
            catch (Exception)
            {
                main.GetError($"Failed Launching {modpack}!");
            }
        }
Пример #6
0
 public MainWindow()
 {
     InitializeComponent();
     // Get the versions for the ComboBox
     var McPath   = Minecraft.GetOSDefaultPath();
     var Launcher = new CMLauncher(McPath);
 }
Пример #7
0
        async Task StartAsync(MSession session) // async version
        {
            var path     = new MinecraftPath();
            var launcher = new CMLauncher(path);

            System.Net.ServicePointManager.DefaultConnectionLimit = 256;

            var versions = await launcher.GetAllVersionsAsync();

            foreach (var item in versions)
            {
                Console.WriteLine(item.Type + " " + item.Name);
            }

            launcher.FileChanged     += Downloader_ChangeFile;
            launcher.ProgressChanged += Downloader_ChangeProgress;

            Console.WriteLine("input version (example: 1.12.2) : ");
            var versionName = Console.ReadLine();
            var process     = await launcher.CreateProcessAsync(versionName, new MLaunchOption
            {
                Session      = session,
                MaximumRamMb = 1024
            });

            Console.WriteLine(process.StartInfo.Arguments);
            process.Start();
        }
Пример #8
0
        async Task Start(MSession session)
        {
            var path = MinecraftPath.GetOSDefaultPath();
            var game = new MinecraftPath(path);

            // Create CMLauncher instance
            var launcher = new CMLauncher(game);

            // if you want to download with parallel downloader, add below code :
            System.Net.ServicePointManager.DefaultConnectionLimit = 256;

            launcher.ProgressChanged += Downloader_ChangeProgress;
            launcher.FileChanged     += Downloader_ChangeFile;

            Console.WriteLine($"{launcher.MinecraftPath.BasePath} adresine kuruldu.");

            // Get all installed profiles and load all profiles from mojang server
            var versions = await launcher.GetAllVersionsAsync();

            foreach (var item in versions) // Display all profiles
            {
                // You can filter snapshots and old versions to add if statement :
                if (item.MType == CmlLib.Core.Version.MVersionType.Release || item.MType == CmlLib.Core.Version.MVersionType.Custom)
                {
                    List <string> list = new List <string> {
                        item.Type + " " + item.Name
                    };

                    list.ForEach(i => Console.Write("{0}\n", i));
                }
            }

            var launchOption = new MLaunchOption
            {
                MaximumRamMb = 1024,
                Session      = session,
            };


            Console.WriteLine("Versiyon yazın (örnek 1.12.2): ");
            var process = await launcher.CreateProcessAsync(Console.ReadLine(), launchOption);

            //var process = launcher.CreateProcess("1.16.2", "33.0.5", launchOption);
            Console.WriteLine(process.StartInfo.Arguments);

            // Below codes are print game logs in Console.
            var processUtil = new CmlLib.Utils.ProcessUtil(process);

            processUtil.OutputReceived += (s, e) => Console.WriteLine(e);
            processUtil.StartWithEvents();
            process.WaitForExit();

            // or just start it without print logs
            // process.Start();

            Console.ReadLine();
            return;
        }
Пример #9
0
        async Task TestAll(MSession session)
        {
            var path = MinecraftPath.GetOSDefaultPath();
            var game = new MinecraftPath(path);

            var launcher = new CMLauncher(game);

            System.Net.ServicePointManager.DefaultConnectionLimit = 256;
            launcher.FileDownloader = new AsyncParallelDownloader();

            launcher.ProgressChanged += Downloader_ChangeProgress;
            launcher.FileChanged     += Downloader_ChangeFile;

            Console.WriteLine($"Initialized in {launcher.MinecraftPath.BasePath}");

            var launchOption = new MLaunchOption
            {
                MaximumRamMb = 1024,
                Session      = session,
            };

            var versions = await launcher.GetAllVersionsAsync();

            foreach (var item in versions)
            {
                Console.WriteLine(item.Type + " " + item.Name);

                if (!item.IsLocalVersion)
                {
                    continue;
                }

                var process = launcher.CreateProcess(item.Name, launchOption);

                //var process = launcher.CreateProcess("1.16.2", "33.0.5", launchOption);
                Console.WriteLine(process.StartInfo.Arguments);

                // Below codes are print game logs in Console.
                var processUtil = new CmlLib.Utils.ProcessUtil(process);
                processUtil.OutputReceived += (s, e) => Console.WriteLine(e);
                processUtil.StartWithEvents();

                Thread.Sleep(1000 * 15);

                if (process.HasExited)
                {
                    Console.WriteLine("FAILED!!!!!!!!!");
                    Console.ReadLine();
                }

                process.Kill();
                process.WaitForExit();
            }

            return;
        }
Пример #10
0
        private async Task initializeLauncher(MinecraftPath path)
        {
            txtPath.Text  = path.BasePath;
            this.gamePath = path;

            launcher                  = new CMLauncher(path);
            launcher.FileChanged     += Launcher_FileChanged;
            launcher.ProgressChanged += Launcher_ProgressChanged;
            await refreshVersions(null);
        }
Пример #11
0
        private void LaunchClick(object sender, RoutedEventArgs e)
        {
            LaunchProgress.Opacity = 100;
            var th = new Thread(new ThreadStart(delegate
            {
                string selectedver = "";

                Application.Current.Dispatcher.Invoke((Action) delegate {
                    LaunchButton.IsEnabled = false;
                    selectedver            = versionList.Text;
                });
                var ThisThreadOptions = new MLaunchOption();
                Application.Current.Dispatcher.Invoke(delegate
                {
                    int screenHeight = 0;
                    int screenWidth  = 0;
                    int MaxRamMB     = Convert.ToInt32(MaxMemSlider.Value);
                    try
                    {
                        screenHeight = Convert.ToInt32(ScreenHeightBox.Text);
                        screenWidth  = Convert.ToInt32(ScreenWidthBox.Text);
                    }
                    catch
                    {
                        screenHeight = 0;
                        screenWidth  = 0;
                    }

                    var launchOptions = new MLaunchOption
                    {
                        JavaPath     = JavaPathBox.Text,
                        ServerIp     = ServerIPBox.Text,
                        ScreenHeight = screenHeight,
                        ScreenWidth  = screenWidth,
                        MaximumRamMb = MaxRamMB,
                        Session      = MainSession,
                        JVMArguments = CustomArgsBox.Text.Split(" ")
                    };
                    ThisThreadOptions = launchOptions;
                });
                CMLauncher launcher       = new CMLauncher(Minecraft.GetOSDefaultPath());
                launcher.ProgressChanged += Launcher_ProgressChanged;
                launcher.FileChanged     += Launcher_FileChanged;
                var process = launcher.CreateProcess(selectedver, ThisThreadOptions);
                process.Start();

                Application.Current.Dispatcher.Invoke((Action) delegate {
                    LaunchButton.IsEnabled    = true;
                    LaunchProgress.Visibility = Visibility.Hidden;
                    LaunchLog.Visibility      = Visibility.Hidden;
                });
            }));

            th.Start();
        }
Пример #12
0
        public MainWindow()
        {
            InitializeComponent();
            Instance = this;
            Accounts.LoadAccounts();
            CMLauncher = new CMLauncher(new MinecraftPath(Directory.GetCurrentDirectory() + "/Data/Game", Directory.GetCurrentDirectory() + "/Data/Assets"));
            TryAutoLogin();

            JObject Object = JObject.Parse(File.ReadAllText("Config.json"));

            ForgeInstalled = (bool)Object["ForgeInstalled"];
        }
Пример #13
0
        private void reloadVersions()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\MaiksLauncher\";

            File.WriteAllText(path + @"VersionList.mvl", String.Empty);
            var McPath = Minecraft.GetOSDefaultPath();

            launcher = new CMLauncher(McPath);
            // you must write this because of cmllib.core bug. it will be fixed soon
            launcher.ProgressChanged += Launcher_ProgressChanged;
            launcher.FileChanged     += Launcher_FileChanged;
            launcher.UpdateProfiles();
            int MTypeAmount = 0;

            foreach (var profile in launcher.Profiles)
            {
                if (profile.MType == MProfileType.Release)
                {
                    MTypeAmount++;
                }
            }
            string[] vers  = new string[MTypeAmount];// this code will block ui, so it should run in thread
            int      index = 0;

            foreach (var profile in launcher.Profiles)
            {
                if (profile.MType == MProfileType.Release)
                {
                    vers[index] = profile.Name; index++;
                }
            }

            StreamWriter sw = new StreamWriter(path + @"VersionList.mvl");

            foreach (string VARIABLE in vers)
            {
                sw.WriteLine(VARIABLE);
            }
            sw.Close();
            Application.Current.Dispatcher.Invoke(delegate
            {
                versionList.Items.Clear();
                foreach (string ver in vers)
                {
                    versionList.Items.Add(ver);
                }
            });
        }
Пример #14
0
        private void InitializeLauncher()
        {
            Launcher = new CMLauncher(Txt_Path.Text);
            //Launcher.Minecraft.SetAssetsPath(Minecraft.GetOSDefaultPath() + "/assets");

            Launcher.FileChanged     += Launcher_FileChanged;
            Launcher.ProgressChanged += Launcher_ProgressChanged;
            var versions = Launcher.UpdateProfileInfos();

            Invoke(new Action(() =>
            {
                Cb_Version.Items.Clear();
                foreach (var item in versions)
                {
                    Cb_Version.Items.Add(item.Name);
                }
            }));
        }
Пример #15
0
        public string Launch(string username, string password, int memory, string version, bool fullScreen)
        {
            var account = new MLogin().Authenticate(username, password);

            if (!account.IsSuccess)
            {
                return(account.Result.ToString() + '\n' + account.ErrorMessage);
            }
            var session = account.Session;
            var mcp     = new MinecraftPath(Path.Combine(Utility.GetWorkingDir(), ".minecraft"));

            ChangeOption(mcp.BasePath, Thread.CurrentThread.CurrentUICulture.Name.Replace('-', '_').ToLower());
            var launcher = new CMLauncher(mcp);

            launcher.FileChanged += (e) => {
                LFileKind          = e.FileKind.ToString();
                LFileName          = e.FileName;
                LProgressedFileCnt = e.ProgressedFileCount.ToString();
                LTotFileCnt        = e.TotalFileCount.ToString();
            };
            launcher.ProgressChanged += (sender, e) => {
                LProgressPercentage = e.ProgressPercentage.ToString();
            };
            var launchOption = new MLaunchOption
            {
                MaximumRamMb = memory,
                Session      = session,
                FullScreen   = fullScreen,
                ServerIp     = "124.71.131.172",
                ServerPort   = 25565,
                JavaPath     = Utility.GetJava(launcher),
                JVMArguments = new string[] {
                    "-javaagent:../nide8auth.jar=28f8f58a8a7f11e88feb525400b59b6a",
                    "-Dnide8auth.client=true"
                }
            };
            var process = launcher.CreateProcess(version, launchOption);

            Console.WriteLine("[Launch] FileName: " + process.StartInfo.FileName);
            Console.WriteLine("[Launch] Arguments: " + process.StartInfo.Arguments);
            Console.WriteLine("[Launch] WorkingDirectory: " + process.StartInfo.WorkingDirectory);
            process.Start();
            return(string.Empty);
        }
        private void MainLauncher_Load(object sender, EventArgs e)
        {
            string path = Minecraft.GetOSDefaultPath();

            Data.MC_OS_PATH = path;
            CMLauncher launcher = new CMLauncher(path);

            launcher.UpdateProfiles();
            Data.launcher = launcher;
            if (File.Exists("mars_client\\serverip.ser"))
            {
                string ip = File.ReadAllText("mars_client\\serverip.ser");
                Data.serverIP = ip;
            }
            if (File.Exists("mars_client\\version.ser"))
            {
                string ver = File.ReadAllText("mars_client\\version.ser");
                Data.versionString = ver;
            }
        }
Пример #17
0
        // this code is from README.md

        async Task QuickStart()
        {
            //var path = new MinecraftPath("game_directory_path");
            var path = new MinecraftPath(); // use default directory

            var launcher = new CMLauncher(path);

            launcher.FileChanged += (e) =>
            {
                Console.WriteLine("[{0}] {1} - {2}/{3}", e.FileKind.ToString(), e.FileName, e.ProgressedFileCount, e.TotalFileCount);
            };
            launcher.ProgressChanged += (s, e) =>
            {
                Console.WriteLine("{0}%", e.ProgressPercentage);
            };

            var versions = await launcher.GetAllVersionsAsync();

            foreach (var item in versions)
            {
                Console.WriteLine(item.Name);
            }

            var launchOption = new MLaunchOption
            {
                MaximumRamMb = 1024,
                Session      = MSession.GetOfflineSession("hello"), // Login Session. ex) Session = MSession.GetOfflineSession("hello")

                //ScreenWidth = 1600,
                //ScreenHeigth = 900,
                //ServerIp = "mc.hypixel.net"
            };

            // launch vanila
            var process = await launcher.CreateProcessAsync("1.15.2", launchOption);

            process.Start();
        }
Пример #18
0
        public Process Start(Server server)
        {
            System.Net.ServicePointManager.DefaultConnectionLimit = 256;

            var game     = new MinecraftPath(path);
            var launcher = new CMLauncher(game);

            launcher.ProgressChanged += Download_Progress;
            launcher.FileChanged     += Download_ChangeFile;

            string version = "";

            if (server.TYPE == "forge")
            {
                version = FindForgeVersion(server.VERSION);

                if (version == "")
                {
                    return(null);
                }
            }
            else
            {
                version = server.VERSION;
            }

            var lv = new LocalVersionLoader(game).GetVersionMetadatas();

            var findVersion = lv.GetVersion(version);

            if (findVersion == null)
            {
                var findMVersion = lv.GetVersionMetadata(version);

                if (findMVersion != null)
                {
                    findMVersion.Save(game);
                }
                else
                {
                    var findWVersion = new MojangVersionLoader().GetVersionMetadatas().GetVersionMetadata(version);

                    if (findWVersion != null)
                    {
                        findWVersion.Save(game);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            var launchOption = new MLaunchOption
            {
                ServerIp            = server.IP,
                ServerPort          = server.PORT,
                MaximumRamMb        = ram,
                Session             = se,
                Path                = game,
                StartVersion        = findVersion,
                GameLauncherName    = "JML",
                GameLauncherVersion = "1.0"
            };

            var process = launcher.CreateProcess(launchOption);

            process.Start();

            return(process);
        }
Пример #19
0
        public Process Start(string _version)
        {
            System.Net.ServicePointManager.DefaultConnectionLimit = 256;

            var game     = new MinecraftPath(path);
            var launcher = new CMLauncher(game);

            launcher.ProgressChanged += Download_Progress;
            launcher.FileChanged     += Download_ChangeFile;

            var lv = new LocalVersionLoader(game).GetVersionMetadatas();

            MVersion findVersion = null;

            try
            {
                findVersion = lv.GetVersion(_version);
            }
            catch (KeyNotFoundException)
            {
            }


            //var findVersion = lv.GetVersion(_version);

            if (findVersion == null)
            {
                MVersionMetadata findMVersion = null;

                try
                {
                    findMVersion = lv.GetVersionMetadata(_version);
                }
                catch (KeyNotFoundException)
                {
                }

                if (findMVersion != null)
                {
                    findMVersion.Save(game);
                }
                else
                {
                    var findWVersion = new MojangVersionLoader().GetVersionMetadatas().GetVersionMetadata(_version);

                    if (findWVersion != null)
                    {
                        findWVersion.Save(game);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            try
            {
                findVersion = lv.GetVersion(_version);
            }
            catch (KeyNotFoundException)
            {
                return(null);
            }

            var launchOption = new MLaunchOption
            {
                MaximumRamMb        = ram,
                Session             = se,
                Path                = game,
                StartVersion        = findVersion,
                GameLauncherName    = "JML",
                GameLauncherVersion = "1.0"
            };

            MLaunch launch  = new MLaunch(launchOption);
            var     process = launch.GetProcess();

            process.Start();

            //Process process = launcher.CreateProcess(launchOption);
            //process.Start();

            return(process);
        }
Пример #20
0
        void Start(MSession session)
        {
            // Initializing Launcher

            // Set minecraft home directory
            // MinecraftPath.GetOSDefaultPath() return default minecraft BasePath of current OS.
            // https://github.com/AlphaBs/CmlLib.Core/blob/master/CmlLib/Core/MinecraftPath.cs

            // You can set this path to what you want like this :
            //var path = "./testdir";
            var path = MinecraftPath.GetOSDefaultPath();
            var game = new MinecraftPath(path);

            // Create CMLauncher instance
            var launcher = new CMLauncher(game);

            // if you want to download with parallel downloader, add below code :
            System.Net.ServicePointManager.DefaultConnectionLimit = 256;

            launcher.ProgressChanged += Downloader_ChangeProgress;
            launcher.FileChanged     += Downloader_ChangeFile;

            Console.WriteLine($"Initialized in {launcher.MinecraftPath.BasePath}");

            // Get all installed profiles and load all profiles from mojang server
            var versions = launcher.GetAllVersions();

            foreach (var item in versions) // Display all profiles
            {
                // You can filter snapshots and old versions to add if statement :
                // if (item.MType == MProfileType.Custom || item.MType == MProfileType.Release)
                Console.WriteLine(item.Type + " " + item.Name);
            }

            var launchOption = new MLaunchOption
            {
                MaximumRamMb = 1024,
                Session      = session,

                //ScreenWidth = 1600,
                //ScreenHeight = 900,
                //ServerIp = "mc.hypixel.net",
                //MinimumRamMb = 102,
                //FullScreen = true,

                // More options:
                // https://github.com/AlphaBs/CmlLib.Core/wiki/MLaunchOption
            };

            // download essential files (ex: vanilla libraries) and create game process.

            // var process = await launcher.CreateProcessAsync("1.15.2", launchOption); // vanilla
            // var process = await launcher.CreateProcessAsync("1.12.2-forge1.12.2-14.23.5.2838", launchOption); // forge
            // var process = await launcher.CreateProcessAsync("1.12.2-LiteLoader1.12.2"); // liteloader
            // var process = await launcher.CreateProcessAsync("fabric-loader-0.11.3-1.16.5") // fabric-loader

            Console.WriteLine("input version (example: 1.12.2) : ");
            var process = launcher.CreateProcess(Console.ReadLine(), launchOption);

            //var process = launcher.CreateProcess("1.16.2", "33.0.5", launchOption);
            Console.WriteLine(process.StartInfo.Arguments);

            // Below codes are print game logs in Console.
            var processUtil = new CmlLib.Utils.ProcessUtil(process);

            processUtil.OutputReceived += (s, e) => Console.WriteLine(e);
            processUtil.StartWithEvents();
            process.WaitForExit();

            // or just start it without print logs
            // process.Start();

            Console.ReadLine();
        }
Пример #21
0
        void Start(MSession session)
        {
            // Initializing Launcher

            // Set minecraft home directory
            // MinecraftPath.GetOSDefaultPath() return default minecraft BasePath of current OS.
            // https://github.com/AlphaBs/CmlLib.Core/blob/master/CmlLib/Core/MinecraftPath.cs

            // You can set this path to what you want like this :
            // var path = Environment.GetEnvironmentVariable("APPDATA") + "\\.mylauncher";
            var path = MinecraftPath.GetOSDefaultPath();
            var game = new MinecraftPath(path);

            // Create CMLauncher instance
            var launcher = new CMLauncher(game);

            launcher.ProgressChanged += Downloader_ChangeProgress;
            launcher.FileChanged     += Downloader_ChangeFile;
            launcher.LogOutput       += (s, e) => Console.WriteLine(e);

            Console.WriteLine($"Initialized in {launcher.MinecraftPath.BasePath}");

            var versions = launcher.GetAllVersions(); // Get all installed profiles and load all profiles from mojang server

            foreach (var item in versions)            // Display all profiles
            {
                // You can filter snapshots and old versions to add if statement :
                // if (item.MType == MProfileType.Custom || item.MType == MProfileType.Release)
                Console.WriteLine(item.Type + " " + item.Name);
            }

            var launchOption = new MLaunchOption
            {
                MaximumRamMb = 1024,
                Session      = session,

                // More options:
                // https://github.com/AlphaBs/CmlLib.Core/wiki/MLaunchOption
            };

            // (A) checks forge installation and install forge if it was not installed.
            // (B) just launch any versions without installing forge, but it can still launch forge already installed.
            // Both methods automatically download essential files (ex: vanilla libraries) and create game process.

            // (A) download forge and launch
            var process = launcher.CreateProcess("1.7.10", "10.13.4.1614", launchOption);

            // (B) launch vanilla version
            // var process = launcher.CreateProcess("1.15.2", launchOption);

            // If you have already installed forge, you can launch it directly like this.
            // var process = launcher.CreateProcess("1.12.2-forge1.12.2-14.23.5.2838", launchOption);

            // launch by user input
            //Console.WriteLine("input version (example: 1.12.2) : ");
            //var process = launcher.CreateProcess(Console.ReadLine(), launchOption);

            //var process = launcher.CreateProcess("1.16.2", "33.0.5", launchOption);
            Console.WriteLine(process.StartInfo.Arguments);

            // Below codes are print game logs in Console.
            var processUtil = new CmlLib.Utils.ProcessUtil(process);

            processUtil.OutputReceived += (s, e) => Console.WriteLine(e);
            processUtil.StartWithEvents();
            process.WaitForExit();

            // or just start it without print logs
            // process.Start();

            Console.ReadLine();

            return;
        }
Пример #22
0
        private async void Initialize()
        {
            await Task.Delay(600);

            try
            {
                using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                {
                    Client.Connect();

                    Client.Disconnect();
                }
            }
            catch
            {
                ProgressText.Text = "Отсутствует интернет-подключение!";
                await Task.Delay(2000);

                DoubleAnimation OpacityAnimation = new DoubleAnimation();
                OpacityAnimation.From     = this.Opacity;
                OpacityAnimation.To       = 0;
                OpacityAnimation.Duration = TimeSpan.FromSeconds(0.5);
                this.BeginAnimation(Window.OpacityProperty, OpacityAnimation);

                await Task.Delay(500);

                Environment.Exit(0);
            }

            DoubleAnimation WidthAnimation = new DoubleAnimation();

            WidthAnimation.From     = ProgressBar.Width;
            WidthAnimation.To       = 80;
            WidthAnimation.Duration = TimeSpan.FromSeconds(0.5);
            ProgressBar.BeginAnimation(Border.WidthProperty, WidthAnimation);
            for (byte i = 0; i <= 25; i++)
            {
                ProgressText.Text = i.ToString() + "%";
                await Task.Delay(15);
            }
            await Task.Delay(800);

            ProgressText.Text = "Установка лаунчера...";


            WidthAnimation.From     = ProgressBar.Width;
            WidthAnimation.To       = 160;
            WidthAnimation.Duration = TimeSpan.FromSeconds(0.5);
            ProgressBar.BeginAnimation(Border.WidthProperty, WidthAnimation);
            for (byte i = 25; i <= 50; i++)
            {
                ProgressText.Text = i.ToString() + "%";
                await Task.Delay(15);
            }
            await Task.Delay(800);

            WidthAnimation.From     = ProgressBar.Width;
            WidthAnimation.To       = 240;
            WidthAnimation.Duration = TimeSpan.FromSeconds(0.5);
            ProgressBar.BeginAnimation(Border.WidthProperty, WidthAnimation);
            for (byte i = 50; i <= 75; i++)
            {
                ProgressText.Text = i.ToString() + "%";
                await Task.Delay(15);
            }
            await Task.Delay(800);

            if (!Directory.Exists(TotalPath + @"/Resource"))
            {
                try
                {
                    Directory.CreateDirectory(TotalPath + @"/Resource");

                    if (Directory.Exists(TotalPath + @"/Resource"))
                    {
                        Directory.CreateDirectory(TotalPath + @"/Resource/Fonts");

                        Directory.CreateDirectory(TotalPath + @"/Resource/Images");

                        try
                        {
                            using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                            {
                                Client.Connect();

                                using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Resource/Images/SteveAvatar.png"))
                                {
                                    Client.DownloadFile("/launcher/Resource/Images/SteveAvatar.png", fileStream);
                                }

                                Client.Disconnect();
                            }
                        }
                        catch { }

                        Directory.CreateDirectory(TotalPath + @"/Resource/Sounds");

                        Directory.CreateDirectory(TotalPath + @"/Resource/Videos");
                    }
                }
                catch { }
            }
            else
            {
                if (!Directory.Exists(TotalPath + @"/Resource/Fonts"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Resource/Fonts");
                }

                if (!Directory.Exists(TotalPath + @"/Resource/Images"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Resource/Images");

                    if (!File.Exists(TotalPath + @"/Resource/Images/SteveAvatar.png"))
                    {
                        try
                        {
                            using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                            {
                                Client.Connect();

                                using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Resource/Images/SteveAvatar.png"))
                                {
                                    Client.DownloadFile("/launcher/Resource/Images/SteveAvatar.png", fileStream);
                                }

                                Client.Disconnect();
                            }
                        }
                        catch { }
                    }

                    if (!File.Exists(TotalPath + @"/Resource/Images/BedrockAvatar.png"))
                    {
                        try
                        {
                            using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                            {
                                Client.Connect();

                                using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Resource/Images/BedrockAvatar.png"))
                                {
                                    Client.DownloadFile("/launcher/Resource/Images/BedrockAvatar.png", fileStream);
                                }

                                Client.Disconnect();
                            }
                        }
                        catch { }
                    }
                }
                else
                {
                    if (!File.Exists(TotalPath + @"/Resource/Images/SteveAvatar.png"))
                    {
                        try
                        {
                            using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                            {
                                Client.Connect();

                                using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Resource/Images/SteveAvatar.png"))
                                {
                                    Client.DownloadFile("/launcher/Resource/Images/SteveAvatar.png", fileStream);
                                }

                                Client.Disconnect();
                            }
                        }
                        catch { }
                    }

                    if (!File.Exists(TotalPath + @"/Resource/Images/BedrockAvatar.png"))
                    {
                        try
                        {
                            using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                            {
                                Client.Connect();

                                using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Resource/Images/BedrockAvatar.png"))
                                {
                                    Client.DownloadFile("/launcher/Resource/Images/BedrockAvatar.png", fileStream);
                                }

                                Client.Disconnect();
                            }
                        }
                        catch { }
                    }
                }

                if (!Directory.Exists(TotalPath + @"/Resource/Sounds"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Resource/Sounds");
                }

                if (!Directory.Exists(TotalPath + @"/Resource/Videos"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Resource/Videos");
                }
            }

            ProgressText.Text = "Установка майнкрафта...";

            if (!Directory.Exists(TotalPath + @"/Storage"))
            {
                try
                {
                    Directory.CreateDirectory(TotalPath + @"/Storage");
                    Directory.CreateDirectory(TotalPath + @"/Storage/Saves");
                    Directory.CreateDirectory(TotalPath + @"/Storage/Crashes");
                    Directory.CreateDirectory(TotalPath + @"/Storage/Users");
                    Directory.CreateDirectory(TotalPath + @"/Storage/Stream");

                    try
                    {
                        using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                        {
                            Client.Connect();

                            using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Storage/Stream/MinecraftVersion"))
                            {
                                Client.DownloadFile("/launcher/Storage/Stream/MinecraftVersion", fileStream);
                            }

                            Client.Disconnect();
                        }
                    }
                    catch { }

                    try
                    {
                        using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                        {
                            Client.Connect();

                            using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Storage/Stream/LauncherVersion"))
                            {
                                Client.DownloadFile("/launcher/Storage/Stream/LauncherVersion", fileStream);
                            }

                            Client.Disconnect();
                        }
                    }
                    catch { }
                }
                catch { }
            }
            else
            {
                if (!Directory.Exists(TotalPath + @"/Storage/Saves"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Storage/Saves");
                }

                if (!Directory.Exists(TotalPath + @"/Storage/Crashes"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Storage/Crashes");
                }

                if (!Directory.Exists(TotalPath + @"/Storage/Users"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Storage/Users");
                }

                if (!Directory.Exists(TotalPath + @"/Storage/Stream"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Storage/Stream");
                }

                try
                {
                    using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                    {
                        Client.Connect();

                        using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Storage/Stream/MinecraftVersion"))
                        {
                            Client.DownloadFile("/launcher/Storage/Stream/MinecraftVersion", fileStream);
                        }

                        Client.Disconnect();
                    }
                }
                catch { }

                try
                {
                    using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                    {
                        Client.Connect();

                        using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Storage/Stream/LauncherVersion"))
                        {
                            Client.DownloadFile("/launcher/Storage/Stream/LauncherVersion", fileStream);
                        }

                        Client.Disconnect();
                    }
                }
                catch { }
            }

            string LaunchertVersion;

            try
            {
                FileStream FileStream = new FileStream(TotalPath + @"/Storage/Stream/LaunchertVersion", FileMode.Open, FileAccess.Read);
                using (var StreamReader = new StreamReader(FileStream, Encoding.UTF8))
                {
                    LaunchertVersion = StreamReader.ReadToEnd();
                    LaunchertVersion = LaunchertVersion.Trim();

                    if (LaunchertVersion == "tech")
                    {
                        ProgressText.Text = "Лаунчер закрыт на тех-обслуживание.";

                        await Task.Delay(2000);

                        DoubleAnimation OpacityAnimation = new DoubleAnimation();
                        OpacityAnimation.From     = this.Opacity;
                        OpacityAnimation.To       = 0;
                        OpacityAnimation.Duration = TimeSpan.FromSeconds(0.5);
                        this.BeginAnimation(Window.OpacityProperty, OpacityAnimation);

                        await Task.Delay(500);

                        Environment.Exit(0);
                    }
                }
            }
            catch { }

            string MinecraftVersion;

            try
            {
                FileStream FileStream = new FileStream(TotalPath + @"/Storage/Stream/MinecraftVersion", FileMode.Open, FileAccess.Read);
                using (var StreamReader = new StreamReader(FileStream, Encoding.UTF8))
                {
                    MinecraftVersion = StreamReader.ReadToEnd();
                    MinecraftVersion = MinecraftVersion.Trim();

                    if (MinecraftVersion == null)
                    {
                        MinecraftVersion = "1.12.2";
                    }
                }
            }
            catch
            {
                MinecraftVersion = "1.12.2";
            }

            if (!Directory.Exists(TotalPath + @"/Minecraft"))
            {
                Directory.CreateDirectory(TotalPath + @"/Minecraft");

                try
                {
                    Launcher = new CMLauncher(Directory.GetCurrentDirectory() + @"\Minecraft");

                    MVersion MVersion = Launcher.GetVersion(MinecraftVersion);
                    Launcher.CheckGameFiles(MVersion, false, false);

                    try
                    {
                        using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                        {
                            Client.Connect();

                            using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Minecraft/options.txt"))
                            {
                                Client.DownloadFile("/launcher/Minecraft/options.txt", fileStream);
                            }

                            Client.Disconnect();
                        }
                    }
                    catch { }
                }
                catch { }
            }
            else
            {
                if (Directory.Exists(TotalPath + @"/Minecraft/saves"))
                {
                    Directory.Delete(TotalPath + @"/Minecraft/saves");
                }

                if (!Directory.Exists(TotalPath + @"/Minecraft/assets"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Minecraft/assets");
                }

                if (!Directory.Exists(TotalPath + @"/Minecraft/assets/objects"))
                {
                    Directory.CreateDirectory(TotalPath + @"/Minecraft/assets/objects");
                }

                if (!File.Exists(TotalPath + @"/Minecraft/options.txt"))
                {
                    try
                    {
                        using (SftpClient Client = new SftpClient(Host, Username, Password.Replace("password", "singularity")))
                        {
                            Client.Connect();

                            using (Stream fileStream = File.Create(Environment.CurrentDirectory + @"/Minecraft/options.txt"))
                            {
                                Client.DownloadFile("/launcher/Minecraft/options.txt", fileStream);
                            }

                            Client.Disconnect();
                        }
                    }
                    catch { }
                }

                try
                {
                    CMLauncher Launcher = new CMLauncher(Directory.GetCurrentDirectory() + @"\Minecraft");

                    MVersion MVersion = Launcher.GetVersion(MinecraftVersion);
                    Launcher.CheckGameFiles(MVersion, false, false);
                }
                catch { }
            }

            WidthAnimation.From     = ProgressBar.Width;
            WidthAnimation.To       = 320;
            WidthAnimation.Duration = TimeSpan.FromSeconds(0.5);
            ProgressBar.BeginAnimation(Border.WidthProperty, WidthAnimation);
            for (byte i = 75; i <= 100; i++)
            {
                ProgressText.Text = i.ToString() + "%";
                await Task.Delay(15);
            }
            await Task.Delay(1000);

            LoginWindow LoginWindow = new LoginWindow();

            LoginWindow.Owner  = this;
            this.Visibility    = Visibility.Hidden;
            this.ShowInTaskbar = false;
            LoginWindow.ShowDialog();

            Verification = true;

            this.Owner.ShowInTaskbar = true;
            this.Close();
        }
        /// <summary>
        /// Launch minecraft
        /// </summary>
        /// <param name="session"></param>
        public void LaunchGame(MSession session)
        {
            moddedLauncher.SetStatusBar("Starting Minecraft", GetType(), StatusType.Launching);

            // Initializing Launcher

            // Set minecraft home directory
            // MinecraftPath.GetOSDefaultPath() return default minecraft BasePath of current OS.
            // https://github.com/AlphaBs/CmlLib.Core/blob/master/CmlLib/Core/MinecraftPath.cs

            // You can set this path to what you want like this :
            // var path = Environment.GetEnvironmentVariable("APPDATA") + "\\.mylauncher";
            var gamePath = configuration.GamePath;
            var game     = new MinecraftPath(configuration.ModpackPath)
            {
                Library  = Dir(gamePath + "/libraries"),
                Versions = Dir(gamePath + "/versions"),
                Runtime  = Dir(gamePath + "/runtime"),
            };

            game.SetAssetsPath(gamePath + "/assets");

            // Create CMLauncher instance
            var launcher = new CMLauncher(game);

            launcher.ProgressChanged += moddedLauncher.LauncherDownloadChangeProgress;
            launcher.FileChanged     += moddedLauncher.LauncherDownloadChangeFile;
            launcher.LogOutput       += (s, e) =>
            {
                Console.WriteLine("NO");
                moddedLauncher.GameOutputWriteLine(e);
            };
            moddedLauncher.GameOutputWriteLine($"Initialized in {launcher.MinecraftPath.BasePath}");

            var launchOption = new MLaunchOption
            {
                MaximumRamMb = configuration.Memory,
                Session      = session,
                ScreenHeight = configuration.ResolutionHeight,
                ScreenWidth  = configuration.ResolutionWidth,
                JVMArguments = configuration.JVMArgs.Split(" ")
                               // More options:
                               // https://github.com/AlphaBs/CmlLib.Core/wiki/MLaunchOption
            };

            // (A) checks forge installation and install forge if it was not installed.
            // (B) just launch any versions without installing forge, but it can still launch forge already installed.
            // Both methods automatically download essential files (ex: vanilla libraries) and create game process.
            moddedLauncher.SetStatusBar("Minecraft Starting", GetType(), StatusType.Launching);

            // (A) download forge and launch
            var process = launcher.CreateProcess("1.12.2", "14.23.5.2854", launchOption);

            // (B) launch vanilla version
            // var process = launcher.CreateProcess("1.15.2", launchOption);

            // If you have already installed forge, you can launch it directly like this.
            // var process = launcher.CreateProcess("1.12.2-forge1.12.2-14.23.5.2838", launchOption);

            // launch by user input
            //Console.WriteLine("input version (example: 1.12.2) : ");
            //var process = launcher.CreateProcess(Console.ReadLine(), launchOption);
            moddedLauncher.SetStatusBar("Minecraft Starting", GetType(), StatusType.Launching);

            //var process = launcher.CreateProcess("1.16.2", "33.0.5", launchOption);
            WriteLine(process.StartInfo.Arguments);

            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;
                Thread.Sleep(TimeSpan.FromSeconds(30));
                moddedLauncher.SetStatusBar("Minecraft Started", GetType(), StatusType.Ready);
            }).Start();



            // Below codes are print game logs in Console.
            var processUtil = new CmlLib.Utils.ProcessUtil(process);

            processUtil.OutputReceived += (s, e) =>
            {
                if (!string.IsNullOrEmpty(e))
                {
                    moddedLauncher.GameOutputWriteLine(e);
                }
            };
            processUtil.StartWithEvents();
            process.WaitForExit();

            // or just start it without print logs
            // process.Start();

            Console.ReadLine();

            return;
        }
        private void LaunchButton_Click(object sender, EventArgs e)
        {
            string sptxt = Data.serverIP;

            if (!string.IsNullOrEmpty(sptxt))
            {
                File.WriteAllText("mars_client\\serverip.ser", sptxt);
            }
            else
            {
                File.WriteAllText("mars_client\\serverip.ser", "");
            }
            object _version = Data.versionString;

            if (_version == null)
            {
                MessageBox.Show("Please select a version!", "Mars", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string version = (string)_version;

            File.WriteAllText("mars_client\\version.ser", version);
            CMLauncher launcher = Data.launcher;
            bool       forge    = version.ToLower().Contains("forge");

            OutputManager.ShowConsoleWindow(true);
            Console.WriteLine("[MARS] Setting up launch arguments... Please wait!");

            MSession ssh;

            if (!Data.offline)
            {
                ssh = new MSession();
                Type editor = typeof(MSession);
                editor.GetField("<ClientToken>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ssh, Data.clientToken);
                editor.GetField("<AccessToken>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ssh, Data.accessToken);
                editor.GetField("<Username>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ssh, Data.username);
                editor.GetField("<UUID>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ssh, Data.mcUUID);
            }
            else
            {
                string username = Data.username;
                ssh = MSession.GetOfflineSession(username);
            }

            Console.WriteLine("[MARS] Successfully created session.");

            MLaunchOption options = new MLaunchOption()
            {
                JavaPath     = "java.exe",
                MaximumRamMb = GetInstalledMemoryMB() / 2,
                Session      = ssh,

                VersionType         = version,
                GameLauncherName    = "MarsClient",
                GameLauncherVersion = "1.5",
            };

            Console.WriteLine("[MARS] Assigned launch options.");

            if (forge)
            {
                string[] parts        = version.Split('-');
                string   mcVer        = parts[0];
                string   forgeVer     = parts[2] + "-" + parts[3];
                MProfile forgeProfile = launcher.GetProfile(mcVer, forgeVer);
                options.StartProfile = forgeProfile;
            }
            else
            {
                options.StartProfile = launcher.GetProfile(version);
            }
            if (!string.IsNullOrEmpty(sptxt))
            {
                options.ServerIp = sptxt;
            }

            Console.WriteLine("[MARS] Located target profile. Launching...");
            Console.WriteLine("[MARS] Moving to new thread...");

            Data.hook.OnHookKeyPressed += Hook_OnHookKeyPressed;
            MLaunch launch = new MLaunch(options);

            mcThread = new Thread(new ParameterizedThreadStart(delegate(object obj) {
                MLaunch threadLaunch       = (MLaunch)obj;
                Process pr                 = threadLaunch.GetProcess();
                ProcessStartInfo psi       = pr.StartInfo;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardInput  = true;
                psi.UseShellExecute        = false;
                staticMC = Process.Start(psi);
                staticMC.EnableRaisingEvents = true;

                launched         = true;
                staticMC.Exited += delegate
                {
                    //OutputManager.RemoveConsole();
                    rpcTimer.Stop();
                    Data.rpccli.Dispose();
                    Invoke((MethodInvoker) delegate
                    {
                        minecraftClosed = true;
                    });
                    mcThread.Abort();
                };
                staticMC.OutputDataReceived += (object _, DataReceivedEventArgs _a) =>
                {
                    string txt = _a.Data;
                    OutputManager.ProcessText(txt);
                    if (txt == null)
                    {
                        return;
                    }
                    if (txt.Contains("[Client thread/INFO]: Connecting to"))
                    {
                        int timeind      = txt.IndexOf(']');
                        string a         = txt.Substring(timeind + 38);
                        string b         = a.Split(',')[0];
                        string newserver = "Server: " + b;
                        if (!currentServer.Equals(newserver))
                        {
                            Debug.WriteLine("Connected to: \"" + b + "\"");
                            Console.WriteLine("Connected to: \"" + b + "\"");
                        }
                        currentServer = "Server: " + b;
                    }
                };
                staticMC.BeginOutputReadLine();
            }));
            mcThread.Start(launch);

            int launchWaits = 0;

            while (staticMC == null)
            {
                launchWaits++;
                Console.WriteLine("[MARS] Waiting for process to launch... #{0}", launchWaits);
                Thread.Sleep(250);
            }

            Console.WriteLine("[MARS] Waiting for main window handle...");
            Data.mcProcess = staticMC;
            while (staticMC.MainWindowHandle == IntPtr.Zero)
            {
                Thread.Sleep(100);
            }
            Data.mcWindow = staticMC.MainWindowHandle;

            Console.WriteLine("\n\n[MARS] Got main window handle. Attaching UI framework...");
            Console.WriteLine("[MARS] Building window...\n\n");

            InGameWindow igw = new InGameWindow();

            Data.hud = igw;
            igw.Show();
            SetParent(igw.Handle, Data.mcWindow);
            igw.NowParented();

            Console.WriteLine("[MARS] Begun window message pump.");
            Console.WriteLine("[MARS] Fetching HypixelSelf info...");

            if (File.Exists("mars_client\\hypixelself.ser"))
            {
                Data.player = HypixelSelf.Deserialize(File.ReadAllText
                                                          ("mars_client\\hypixelself.ser"));
            }

            Console.WriteLine("[MARS] Loaded, if any.\n\n");

            Console.WriteLine("[MARS] Finished initialization.");
        }