コード例 #1
0
        private async void SyncForm_Shown(object sender, EventArgs e)
        {
            // Get serverdirectory
            string serverDirectory;

            if (string.IsNullOrEmpty(Settings.serverDirectory))
            {
                serverDirectory = Environment.CurrentDirectory;
            }
            else
            {
                serverDirectory = Settings.serverDirectory;
            }

            // Make sure credentials.json is present
            if (!System.IO.File.Exists(Environment.CurrentDirectory + "\\credentials.json"))
            {
                System.IO.File.WriteAllBytes(Environment.CurrentDirectory + "\\credentials.json", Properties.Resources.credentials);
            }

            UpdateStatusLabel("Authenticating Google Drive...");

            // Authorize
            UserCredential credential;

            using (FileStream stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

            // Create Drive API service.
            DriveService service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            UpdateProgressBar(progressBar.Maximum);
            UpdateStatusLabel("Authenticated Google Drive.");

            if (download)
            {
                UpdateProgressBar(0);
                UpdateStatusLabel("Checking if server is already active...");
                FilesResource.ListRequest request = service.Files.List();
                request.Q      = "name contains 'server-ip='";
                request.Fields = "files(id, name)";
                FileList result = await request.ExecuteAsync();

                if (result != null && result.Files.Count > 0)
                {
                    AlreadyRunningForm arf = new AlreadyRunningForm(result.Files[0].Name.Replace("server-ip=", ""));
                    if (arf.ShowDialog() == DialogResult.No)
                    {
                        syncCompleted = true;
                        Environment.Exit(0);
                        return;
                    }

                    foreach (Google.Apis.Drive.v3.Data.File file in result.Files)
                    {
                        await Task.Run(() => deleteFile(service, file));
                    }
                }

                UpdateSubProgressBar(0);
                UpdateSubStatusLabel("");
                UpdateProgressBar(progressBar.Maximum);
                UpdateStatusLabel("Check complete.");
            }

            if (!Settings.hasCompletedUpload && download)
            {
                DialogResult dr = MessageBox.Show("Upload hasn't completed since the last time you ran the server. Do you want to continue to upload? If not the files on Google Drive will be downloaded.", "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error);

                switch (dr)
                {
                case DialogResult.Yes:
                    download = false;
                    break;

                case DialogResult.No:
                    download = true;
                    break;

                case DialogResult.Cancel:
                    Environment.Exit(0);
                    break;
                }

                Settings.hasCompletedUpload = true;
                Functions.SaveSettings();
            }

            List <Google.Apis.Drive.v3.Data.File> driveFiles = await Task.Run(async() => await getDriveFiles(service));

            FileInfo[] serverFiles = Functions.GetServerFiles(new DirectoryInfo(serverDirectory));

            if (download)
            {
                await Task.Run(async() => await DownloadSync(service, driveFiles, serverDirectory));
            }
            else
            {
                await Task.Run(async() => await UploadSync(service, driveFiles, serverFiles, serverDirectory));
            }

            UpdateSubStatusLabel("");
            UpdateSubProgressBar(subProgressBar.Maximum);
            UpdateProgressBar(progressBar.Maximum);
            UpdateStatusLabel("Sync completed.");
            syncCompleted = true;

            this.Close();
        }
コード例 #2
0
        private async void StartButton_Click(object sender, EventArgs e)
        {
            if (statusLabel.Text != "Offline")
            {
                return;
            }

            serverConsole.Clear();

            if (!System.IO.File.Exists(Settings.ngrokDirectory + "\\ngrok.exe"))
            {
                serverConsole.AppendText("[ERROR] ngrok.exe was not found in the given path! Please check the settings to make sure the path is correct.", Color.Red);
                return;
            }

            if (!System.IO.File.Exists(Settings.serverDirectory + "\\" + Settings.serverFileName))
            {
                serverConsole.AppendText("[ERROR] Server file with name '" + Settings.serverFileName + "' was not found in the given path! Please check the settings to make sure the path and filename are correct!", Color.Red);
                return;
            }

            statusLabel.Text      = "Starting...";
            statusLabel.ForeColor = Color.Orange;
            this.Text             = "Server Console - Starting...";
            this.Icon             = Properties.Resources.server_loading;

            FilesResource.ListRequest listRequest = driveService.Files.List();
            listRequest.Q      = "name contains 'server-ip='";
            listRequest.Fields = "files(id, name)";
            FileList result = await listRequest.ExecuteAsync();

            if (result != null && result.Files.Count > 0)
            {
                AlreadyRunningForm arf = new AlreadyRunningForm(result.Files[0].Name.Replace("server-ip=", ""));
                if (arf.ShowDialog() == DialogResult.No)
                {
                    statusLabel.Text      = "Offline";
                    statusLabel.ForeColor = Color.Red;
                    this.Text             = "Server Console - Offline";
                    this.Icon             = Properties.Resources.server_offline;
                    return;
                }

                foreach (Google.Apis.Drive.v3.Data.File file in result.Files)
                {
                    await Task.Run(() => driveService.Files.Delete(file.Id).Execute());
                }
            }

            Settings.hasCompletedUpload = false;
            Functions.SaveSettings();

            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                if (!System.IO.File.Exists(Settings.ngrokDirectory + "\\OpenTunnel.bat"))
                {
                    StreamWriter sw = new StreamWriter(Settings.ngrokDirectory + "\\OpenTunnel.bat");

                    sw.WriteLine("ngrok tcp -region eu %1");
                    sw.Close();
                }

                Process ipRetriever            = new Process();
                ipRetriever.StartInfo.FileName = Settings.ngrokDirectory + "\\OpenTunnel.bat";
                if (string.IsNullOrEmpty(Settings.ngrokDirectory))
                {
                    ipRetriever.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
                }
                else
                {
                    ipRetriever.StartInfo.WorkingDirectory = Settings.ngrokDirectory;
                }
                ipRetriever.StartInfo.Arguments = Settings.localPort;
                ipRetriever.StartInfo.RedirectStandardOutput = true;
                ipRetriever.StartInfo.UseShellExecute        = false;
                ipRetriever.StartInfo.CreateNoWindow         = true;
                ipRetriever.OutputDataReceived += new DataReceivedEventHandler((_sender, args) =>
                {
                    try
                    {
                        WebClient client = new WebClient();
                        ip = client.DownloadString("http://127.0.0.1:4040/api/tunnels").Split(new string[] { "tcp://" }, StringSplitOptions.None)[1].Split('"')[0];
                        ipLabel.Invoke((MethodInvoker)(() => ipLabel.Text = ip));
                        hasIp            = true;
                        ipCopyTip.Active = true;

                        if (serverIpFile == null)
                        {
                            Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
                            body.Name        = "server-ip=" + ip;
                            body.Description = "File to store the currently active server IP";

                            FilesResource.CreateRequest request = driveService.Files.Create(body);
                            request.Fields = "id";
                            serverIpFile   = request.Execute();
                        }
                    }catch { }
                });

                ipRetriever.Start();
                ipRetriever.BeginOutputReadLine();
                ipRetriever.WaitForExit();
                ipRetriever.Close();
            }).Start();

            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                string memory = Settings.memSize.ToString() + "G";

                server = new Process();
                server.StartInfo.FileName = "java.exe";
                if (string.IsNullOrEmpty(Settings.serverDirectory))
                {
                    server.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
                }
                else
                {
                    server.StartInfo.WorkingDirectory = Settings.serverDirectory;
                }
                server.StartInfo.Arguments = "-server -Xmx" + memory + " -XX:+UseG1GC -Xms" + memory + " -Dsun.rmi.dgc.server.gcInterval=2147483646 -XX:+UnlockExperimentalVMOptions -XX:G1NewSizePercent=20 -XX:G1ReservePercent=20 -XX:MaxGCPauseMillis=50 -XX:G1HeapRegionSize=32M -Dfml.queryResult=confirm -jar \"" + Settings.serverFileName + "\" nogui";//Settings.memSize + " \"" + Settings.serverFileName + "\"";
                server.StartInfo.RedirectStandardOutput = true;
                server.StartInfo.RedirectStandardInput  = true;
                server.StartInfo.UseShellExecute        = false;
                server.StartInfo.CreateNoWindow         = true;
                server.OutputDataReceived += new DataReceivedEventHandler((_sender, args) =>
                {
                    if (!string.IsNullOrEmpty(args.Data))
                    {
                        if (args.Data.Contains("[Server thread/WARN]") || args.Data.Contains("[main/WARN]"))
                        {
                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(args.Data, Color.Orange)));
                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(Environment.NewLine)));
                        }
                        else if (args.Data.Contains("[Server thread/ERROR]") || args.Data.Contains("[main/ERROR]"))
                        {
                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(args.Data, Color.Red)));
                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(Environment.NewLine)));

                            if (args.Data.Contains("crash"))
                            {
                                statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = "Offline"));
                                statusLabel.Invoke((MethodInvoker)(() => statusLabel.ForeColor = Color.Red));
                                this.Invoke((MethodInvoker)(() => this.Text = "Server Console - Offline"));

                                serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText("[CRASH] The server crashed. Check the crash report.", Color.Red)));
                                serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(Environment.NewLine)));

                                server.Kill();
                            }
                        }
                        else if (args.Data.Contains("[INDICATOR FOR SERVER MANAGER THAT SERVER HAS STARTED]"))
                        {
                            statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = "Online"));
                            statusLabel.Invoke((MethodInvoker)(() => statusLabel.ForeColor = Color.Green));
                            this.Invoke((MethodInvoker)(() => this.Text = "Server Console - Online"));
                            this.Invoke((MethodInvoker)(() => this.Icon = Properties.Resources.server_online));

                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText("Server done loading!", Color.Green)));
                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(Environment.NewLine)));
                        }
                        else
                        {
                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(args.Data)));
                            serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(Environment.NewLine)));
                        }

                        if (args.Data.Contains("[Server thread/INFO] [icbmclassic]: Stopping threads"))
                        {
                            statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = "Stopping..."));
                            statusLabel.Invoke((MethodInvoker)(() => statusLabel.ForeColor = Color.Orange));
                            this.Invoke((MethodInvoker)(() => this.Text = "Server Console - Stopping..."));
                            this.Invoke((MethodInvoker)(() => this.Icon = Properties.Resources.server_loading));
                        }

                        if (args.Data.Contains("joined the game") && args.Data.Contains("[Server thread/INFO] [minecraft/DedicatedServer]") && args.Data.Split(' ').Length == 8 && !args.Data.Split(' ')[4].Contains("<"))
                        {
                            onlinePlayers.Add(args.Data.Split(' ')[4]);
                            UpdateOnlinePlayers();
                        }

                        if (args.Data.Contains("left the game") && args.Data.Contains("[Server thread/INFO] [minecraft/DedicatedServer]") && args.Data.Split(' ').Length == 8 && !args.Data.Split(' ')[4].Contains("<"))
                        {
                            onlinePlayers.Remove(args.Data.Split(' ')[4]);
                            UpdateOnlinePlayers();
                        }
                    }
                });

                server.Start();
                server.BeginOutputReadLine();
                serverInput           = server.StandardInput;
                serverInput.AutoFlush = true;
                serverRunning         = true;
                CreateRAMCheckThread();
                updateRamThread.Start();
                SendCommand("say [INDICATOR FOR SERVER MANAGER THAT SERVER HAS STARTED]", false);
                server.WaitForExit();
                serverRunning = false;
                ramLabel.Invoke((MethodInvoker)(() => ramLabel.Text = "0/" + (Settings.memSize * 1024) + " MB RAM"));
                serverInput.Close();
                server.Close();
                server.Dispose();
                statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = "Offline"));
                statusLabel.Invoke((MethodInvoker)(() => statusLabel.ForeColor = Color.Red));
                this.Invoke((MethodInvoker)(() => this.Text = "Server Console - Offline"));
                this.Invoke((MethodInvoker)(() => this.Icon = Properties.Resources.server_offline));

                serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText("Server stopped.", Color.Red)));
                serverConsole.Invoke((MethodInvoker)(() => serverConsole.AppendText(Environment.NewLine)));

                onlinePlayers.Clear();
                UpdateOnlinePlayers();
            }).Start();
        }