Пример #1
0
        /// <summary>
        /// 从缓存中取系统参数
        /// </summary>
        /// <param name="distributorID"></param>
        /// <param name="companyID"></param>
        /// <param name="keyName"></param>
        /// <returns>string类型的参数值</returns>
        protected string GetSysData(int distributorID, string keyName)
        {
            string retVal = "";

            if (this.mUserInfo == null)
            {
                retVal = "";
                return(retVal);
            }

            try
            {
                DataTable dtSysData;

                if (ServerApp.GetInstance().SysDataCache.TryGetValue(this.mUserInfo.CompanyID, out dtSysData))
                {
                    DataRow[] rows = dtSysData.Select("DistributorID = " + distributorID.ToString() + " and KeyName='" + keyName + "'");
                    if (rows == null || rows.Length == 0)
                    {
                        retVal = "";
                    }
                    else
                    {
                        retVal = rows[0]["KeyValue"].ToString();
                    }
                }
            }
            catch
            {
                throw;
            }

            return(retVal);
        }
Пример #2
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public FrmModules(IAdminContext adminContext, ServerApp serverApp)
     : this()
 {
     this.adminContext = adminContext ?? throw new ArgumentNullException(nameof(adminContext));
     this.serverApp    = serverApp ?? throw new ArgumentNullException(nameof(serverApp));
     serverConfig      = serverApp.AppConfig;
 }
        private async void BackupServer_Click(object sender, RoutedEventArgs e)
        {
            var server = ((Server)((Button)e.Source).DataContext);

            if (server == null)
            {
                return;
            }

            try
            {
                var app = new ServerApp(true)
                {
                    DeleteOldServerBackupFiles = !Config.Default.AutoBackup_EnableBackup,
                    SendEmails    = false,
                    OutputLogs    = false,
                    ServerProcess = ServerProcessType.Backup,
                };

                var profile = ServerProfileSnapshot.Create(server.Profile);

                var exitCode = await Task.Run(() => app.PerformProfileBackup(profile));

                if (exitCode != ServerApp.EXITCODE_NORMALEXIT && exitCode != ServerApp.EXITCODE_CANCELLED)
                {
                    throw new ApplicationException($"An error occured during the backup process - ExitCode: {exitCode}");
                }

                MessageBox.Show(_globalizer.GetResourceString("ServerSettings_BackupServer_SuccessfulLabel"), _globalizer.GetResourceString("ServerSettings_BackupServer_Title"), MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_BackupServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #4
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Unicode;
            Console.Title          = "Grand Cheese Login";

            Console.WriteLine("  ////////////////////////////////////////");
            Console.WriteLine("       Grand Cheese Season V / Center     ");
            Console.WriteLine("  ////////////////////////////////////////");
            Console.WriteLine();

            Log.Get().Info("Getting server list...");
            using (var db = Database.Get())
            {
                var servers = db.Query <Server>("SELECT * FROM servers").ToArray();

                foreach (var server in servers)
                {
                    Data.Servers.Add(server);
                }
            }
            Log.Get().Info("Loaded {0} server{1}.", Data.Servers.Count, Data.Servers.Count == 1 ? "" : "s");

            var serverApp = new ServerApp();

            serverApp.StartServer(9501);

            // This won't work on Mono probably
            while (true)
            {
                Console.ReadLine();
            }
        }
Пример #5
0
        private async void Shutdown_Click(object sender, RoutedEventArgs e)
        {
            if (ShutdownStarted)
            {
                return;
            }

            try
            {
                MessageOutput.Clear();

                ShutdownType = 1;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = System.Windows.Input.Cursors.Wait);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = System.Windows.Input.Cursors.Arrow);

                var app = new ServerApp(true)
                {
                    BackupWorldFile  = this.BackupWorldFile,
                    ShutdownInterval = this.ShutdownInterval,
                    ShutdownReason   = this.ShutdownReason,
                    OutputLogs       = false,
                    SendAlerts       = true,
                    ServerProcess    = RestartServer ? ServerProcessType.Restart : ServerProcessType.Shutdown,
                    ProgressCallback = (p, m, n) => { TaskUtils.RunOnUIThreadAsync(() => { this.AddMessage(m, n); }).DoNotWait(); },
                };

                var profile       = ProfileSnapshot.Create(Server.Profile);
                var restartServer = RestartServer;
                var updateServer  = UpdateServer;

                _shutdownCancellationSource = new CancellationTokenSource();

                var exitCode = await Task.Run(() => app.PerformProfileShutdown(profile, restartServer, updateServer, _shutdownCancellationSource.Token));

                if (exitCode != ServerApp.EXITCODE_NORMALEXIT && exitCode != ServerApp.EXITCODE_CANCELLED)
                {
                    throw new ApplicationException($"An error occured during the shutdown process - ExitCode: {exitCode}");
                }

                ShutdownType = 0;
                // if restarting or updating the server after the shutdown, delay the form closing
                if (restartServer || updateServer)
                {
                    await Task.Delay(5000);
                }

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_ShutdownServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                ShutdownType = 0;
            }
            finally
            {
                _shutdownCancellationSource = null;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = null);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = null);
            }
        }
Пример #6
0
        public AppDisplay(ServerApp serverApp)
        {
            this.PkgId = serverApp.PkgId;
            this.Name = serverApp.AppID;
            this.Version = serverApp.Version;
            this.Size = serverApp.Size;
            this.Category = serverApp.Category;
            var info = serverApp.InfoStr.Split('\n');
            /*if (info.Count() >= 1)
                this.Category = info[0];
            if (info.Count() >= 2)
                this.Version = info[1];*/
            this.ImageUrl = serverApp.IconUrl;

            var localIconFile = ServerSingleton.Instance.ServerClient.LocalIconFile(PkgId);
            if (File.Exists(localIconFile))
            {
                this.ImagePath = localIconFile;
                this.ImageLoaded = true;
            }
            else
            {
                this.ImagePath = "gfx\\Pending.png";
                this.ImageLoaded = false;
            }
        }
Пример #7
0
        public static void SetCreator(BattlegroundId id, string typeName)
        {
            Type type = ServerApp <WCell.RealmServer.RealmServer> .GetType(typeName);

            BattlegroundTemplate template = BattlegroundMgr.GetTemplate(id);

            if (type == (Type)null || template == null)
            {
                object obj1;
                object obj2;
                if (type == (Type)null)
                {
                    obj1 = (object)"type";
                    obj2 = (object)string.Format("({0}) - Please correct it in the Battleground-config file: {1}",
                                                 (object)typeName, (object)InstanceConfigBase <BattlegroundConfig, BattlegroundId> .Filename);
                }
                else
                {
                    obj1 = (object)"Template";
                    obj2 = (object)"<not in DB>";
                }

                BattlegroundMgr.log.Warn("Battleground {0} has invalid {1} {2}", (object)id, obj1, obj2);
            }
            else
            {
                IProducer producer = AccessorMgr.GetOrCreateDefaultProducer(type);
                template.Creator = (BattlegroundCreator)(() => (Battleground)producer.Produce());
            }
        }
Пример #8
0
        /// <summary>
        /// Shutdown the session by killing any remaining processes.
        /// </summary>
        /// <returns></returns>
        public void Shutdown()
        {
            // Kill any remaining client processes
            if (ClientApps != null)
            {
                List <IAppInstance> RunningApps = ClientApps.Where(App => App.HasExited == false).ToList();

                if (RunningApps.Count > 0)
                {
                    Log.Info("Shutting down {0} clients", RunningApps.Count);
                    RunningApps.ForEach(App => App.Kill());
                }
            }

            if (ServerApp != null)
            {
                if (ServerApp.HasExited == false)
                {
                    Log.Info("Shutting down server");
                    ServerApp.Kill();
                }
            }

            // kill anything that's left
            RunningRoles.Where(R => R.AppInstance.HasExited == false).ToList().ForEach(R => R.AppInstance.Kill());

            // Wait for it all to end
            RunningRoles.ToList().ForEach(R => R.AppInstance.WaitForExit());

            Thread.Sleep(3000);
        }
Пример #9
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public FrmGeneralOptions(IAdminContext adminContext, ServerApp serverApp)
     : this()
 {
     this.adminContext = adminContext ?? throw new ArgumentNullException(nameof(adminContext));
     this.serverApp    = serverApp ?? throw new ArgumentNullException(nameof(serverApp));
     serverConfig      = serverApp.AppConfig;
     changing          = false;
 }
Пример #10
0
        static void Main(string[] args)
        {
            Listener listener = new Listener();

            listener.Url  = "localhost";
            listener.Port = "8080";
            ServerApp serverApp = new ServerApp();

            serverApp.StartWebServer(listener);
        }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public FrmArchives(IAdminContext adminContext, ServerApp serverApp)
     : this()
 {
     this.adminContext = adminContext ?? throw new ArgumentNullException(nameof(adminContext));
     this.serverApp    = serverApp ?? throw new ArgumentNullException(nameof(serverApp));
     serverConfig      = serverApp.AppConfig;
     changing          = false;
     archiveClipboard  = null;
     SetColumnNames();
 }
Пример #12
0
        private void FormManagment_FormLoad(object sender, EventArgs e)
        {
            server = new ServerApp(IPAddress.Any, 904)
            {
                status = true
            };
            Task task = new Task(server.ServerRun);

            task.Start();
        }
Пример #13
0
 public static void Main(string[] args)
 {
     if (args.Length > 0 && args[0] == CLIENT_ARG)
     {
         Client.Main(args);
     }
     else
     {
         ServerApp.Main();
     }
 }
        private async Task LoadWorldSaveFiles()
        {
            var cursor = this.Cursor;

            try
            {
                Application.Current.Dispatcher.Invoke(() => this.Cursor = System.Windows.Input.Cursors.Wait);
                await Task.Delay(500);

                WorldSaveFiles.Clear();

                var saveFolder = ServerProfile.GetProfileSavePath(_profile);
                if (!Directory.Exists(saveFolder))
                {
                    return;
                }

                var saveFolderInfo = new DirectoryInfo(saveFolder);
                var mapName        = ServerProfile.GetProfileMapFileName(_profile);
                var mapFileName    = $"{mapName}{Config.Default.MapExtension}";
                var searchPattern  = $"{mapName}*{Config.Default.MapExtension}";

                var saveFiles = saveFolderInfo.GetFiles(searchPattern);
                foreach (var file in saveFiles)
                {
                    WorldSaveFiles.Add(new WorldSaveFile {
                        File = file.FullName, FileName = file.Name, CreatedDate = file.CreationTime, UpdatedDate = file.LastWriteTime, IsArchiveFile = false, IsActiveFile = file.Name.Equals(mapFileName, StringComparison.OrdinalIgnoreCase)
                    });
                }

                var backupFolder = ServerApp.GetServerBackupFolder(_profile.ProfileName);
                if (Directory.Exists(backupFolder))
                {
                    var backupFolderInfo = new DirectoryInfo(backupFolder);
                    searchPattern = $"{mapName}*{Config.Default.BackupExtension}";

                    var backupFiles = backupFolderInfo.GetFiles(searchPattern);
                    foreach (var file in backupFiles)
                    {
                        WorldSaveFiles.Add(new WorldSaveFile {
                            File = file.FullName, FileName = file.Name, CreatedDate = file.CreationTime, UpdatedDate = file.LastWriteTime, IsArchiveFile = true, IsActiveFile = false
                        });
                    }
                }

                WorldSaveFiles.Sort(f => f, new WorldSaveFileComparer());
            }
            finally
            {
                Application.Current.Dispatcher.Invoke(() => this.Cursor = cursor);
            }
        }
Пример #15
0
        public static void SetCreator(MapId id, string typeName)
        {
            Type type = ServerApp <RealmServer> .GetType(typeName);

            if (type == null)
            {
                log.Warn("Invalid Creator for Instance \"" + id + "\": " + typeName +
                         "  - Please correct it in the Instance-config file: " +
                         InstanceConfigBase <InstanceConfig, MapId> .Filename);
            }
            else
            {
                IProducer producer = AccessorMgr.GetOrCreateDefaultProducer(type);
                SetCreator(id, () => (BaseInstance)producer.Produce());
            }
        }
Пример #16
0
        private void Start(string[] args)
        {
            ParseCommandLineArgs(args);

            switch (GetStartAction())
            {
            case Action.START_WEB_APP:
                m_Application = new ServerApp();
                break;

            case Action.FILL_DB:
                m_Application = new FillDBApp();
                break;
            }

            m_Application.Start(args);
        }
Пример #17
0
        /// <summary>
        /// Gets a new instance of the module user interface.
        /// </summary>
        public static bool GetModuleView(IAdminContext adminContext, ServerApp serverApp, string moduleCode,
                                         out ModuleView moduleView, out string message)
        {
            ArgumentNullException.ThrowIfNull(adminContext, nameof(adminContext));
            ArgumentNullException.ThrowIfNull(serverApp, nameof(serverApp));

            if (ModuleFactory.GetModuleView(adminContext.AppDirs.LibDir, moduleCode, out moduleView, out message))
            {
                moduleView.ConfigDataset = adminContext.CurrentProject.ConfigDatabase;
                moduleView.AppDirs       = adminContext.AppDirs.CreateDirsForView(serverApp.ConfigDir);
                moduleView.AppConfig     = serverApp.AppConfig;
                moduleView.LoadDictionaries();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #18
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Unicode;
            Console.Title          = "Grand Cheese Game";

            Console.WriteLine("  ////////////////////////////////////////");
            Console.WriteLine("         Grand Cheese Season V / Game     ");
            Console.WriteLine("  ////////////////////////////////////////");
            Console.WriteLine();

            using (var db = Database.Get())
            {
                var server = db.Query <Server>("SELECT * FROM servers WHERE port = @port",
                                               new { port = 9401 }).FirstOrDefault();

                if (server != null)
                {
                    Data.Data.Server = server;
                }
            }

            var serverApp = new ServerApp
            {
                CreateUserClient = (Client c) =>
                {
                    c.User = new UserClient(c);
                },

                CustomInvoke = (ServerApp app, Client c, Packet p, short opcode) =>
                {
                    if (c.User == null)
                    {
                        c.User = new UserClient(c);
                    }

                    var user   = (UserClient)c.User;
                    var method = app.serverPackets[opcode];

                    Console.WriteLine(method.DeclaringType.Name);

                    switch (method.DeclaringType.Name)
                    {
                    case "KUser":
                        method.Invoke(user.KUser, new object[] { c, p });
                        break;

                    default:
                        if (method.GetParameters().Length == 1)
                        {
                            method.Invoke(null, new object[] { user.KUser });
                        }
                        else
                        {
                            Log.Get().Warn("Unhandled. Attempting to call as static.");
                            method.Invoke(null, new object[] { c, p });
                        }
                        break;
                    }
                }
            };

            serverApp.StartServer(Data.Data.Server.Port, "game");

            // This won't work on Mono probably
            while (true)
            {
                Console.ReadLine();
            }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            _globalizer = GlobalizedApplication.Instance;
            try
            {
                if (!string.IsNullOrWhiteSpace(Config.Default.CultureName))
                {
                    _globalizer.GlobalizationManager.SwitchLanguage(Config.Default.CultureName, true);
                }
            }
            catch (CultureNotFoundException ex)
            {
                // just output the exception message, it should default back to the fallback language.
                Debug.WriteLine(ex.Message);
            }

            if (!string.IsNullOrWhiteSpace(Config.Default.StyleName))
            {
                _globalizer.StyleManager.SwitchStyle($"{Config.Default.StyleName}.xaml");
            }

            Args = string.Join(" ", e.Args);

            // check if we are starting ASM for server restart
            if (e.Args.Any(a => a.Equals(ARG_BETA)))
            {
                BetaVersion = true;
            }

            var installPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            PluginHelper.Instance.BetaEnabled = BetaVersion;
            PluginHelper.Instance.LoadPlugins(installPath, true);

            // check if we are starting ASM for the old server restart - no longer supported
            if (e.Args.Any(a => a.StartsWith(ARG_AUTORESTART)))
            {
                // just exit
                Environment.Exit(0);
            }

            // check if we are starting ASM for server shutdown
            if (e.Args.Any(a => a.StartsWith(ARG_AUTOSHUTDOWN1)))
            {
                var arg      = e.Args.FirstOrDefault(a => a.StartsWith(ARG_AUTOSHUTDOWN1));
                var exitCode = ServerApp.PerformAutoShutdown(arg, ServerApp.ServerProcessType.AutoShutdown1);

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            // check if we are starting ASM for server shutdown
            if (e.Args.Any(a => a.StartsWith(ARG_AUTOSHUTDOWN2)))
            {
                var arg      = e.Args.FirstOrDefault(a => a.StartsWith(ARG_AUTOSHUTDOWN2));
                var exitCode = ServerApp.PerformAutoShutdown(arg, ServerApp.ServerProcessType.AutoShutdown2);

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            // check if we are starting ASM for server updating
            if (e.Args.Any(a => a.Equals(ARG_AUTOUPDATE)))
            {
                var exitCode = ServerApp.PerformAutoUpdate();

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            // check if we are starting ASM for server backups
            if (e.Args.Any(a => a.Equals(ARG_AUTOBACKUP)))
            {
                var exitCode = ServerApp.PerformAutoBackup();

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            // check if we are starting ASM for server updating
            if (e.Args.Any(a => a.Equals(ARG_RCON)))
            {
                var rcon = new OpenRCONWindow();
                rcon.ShowInTaskbar         = true;
                rcon.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                rcon.ShowDialog();

                Config.Default.Save();

                // once we are finished, just exit
                Environment.Exit(0);
            }

            if (Config.Default.RunAsAdministratorPrompt && !SecurityUtils.IsAdministrator())
            {
                var result = MessageBox.Show(_globalizer.GetResourceString("Application_RunAsAdministratorLabel"), _globalizer.GetResourceString("Application_RunAsAdministratorTitle"), MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);

                    // The following properties run the new process as administrator
                    processInfo.UseShellExecute = true;
                    processInfo.Verb            = "runas";
                    processInfo.Arguments       = string.Join(" ", e.Args);

                    // Start the new process
                    try
                    {
                        Process.Start(processInfo);

                        // Shut down the current process
                        Application.Current.Shutdown(0);

                        return;
                    }
                    catch (Exception)
                    {
                        // The user did not allow the application to run as administrator
                        MessageBox.Show(_globalizer.GetResourceString("Application_RunAsAdministrator_FailedLabel"), _globalizer.GetResourceString("Application_RunAsAdministrator_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }

            // check if application is already running
            if (ProcessUtils.IsAlreadyRunning())
            {
                var result = MessageBox.Show(_globalizer.GetResourceString("Application_SingleInstanceLabel"), _globalizer.GetResourceString("Application_SingleInstanceTitle"), MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    if (ProcessUtils.SwitchToCurrentInstance())
                    {
                        // Shut down the current process
                        Application.Current.Shutdown(0);

                        return;
                    }

                    MessageBox.Show(_globalizer.GetResourceString("Application_SingleInstance_FailedLabel"), _globalizer.GetResourceString("Application_SingleInstance_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            ApplicationStarted = true;

            // Initial configuration setting
            if (String.IsNullOrWhiteSpace(Config.Default.DataDir))
            {
                MessageBox.Show(_globalizer.GetResourceString("Application_DataDirectoryLabel"), _globalizer.GetResourceString("Application_DataDirectoryTitle"), MessageBoxButton.OK, MessageBoxImage.Information);

                while (String.IsNullOrWhiteSpace(Config.Default.DataDir))
                {
                    var dialog = new CommonOpenFileDialog();
                    dialog.EnsureFileExists = true;
                    dialog.IsFolderPicker   = true;
                    dialog.Multiselect      = false;
                    dialog.Title            = _globalizer.GetResourceString("Application_DataDirectory_DialogTitle");
                    dialog.InitialDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                    {
                        Environment.Exit(0);
                    }

                    var confirm = MessageBox.Show(String.Format(_globalizer.GetResourceString("Application_DataDirectory_ConfirmLabel"), Path.Combine(dialog.FileName, Config.Default.ProfilesDir), Path.Combine(dialog.FileName, Config.Default.SteamCmdDir)), _globalizer.GetResourceString("Application_DataDirectory_ConfirmTitle"), MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                    if (confirm == MessageBoxResult.Cancel)
                    {
                        Environment.Exit(0);
                    }
                    else if (confirm == MessageBoxResult.Yes)
                    {
                        Config.Default.DataDir = dialog.FileName;
                        ReconfigureLogging();
                        break;
                    }
                }
            }

            Config.Default.ConfigDirectory = Path.Combine(Config.Default.DataDir, Config.Default.ProfilesDir);
            System.IO.Directory.CreateDirectory(Config.Default.ConfigDirectory);
            Config.Default.Save();

            // initialize all the game data
            GameData.Initialize();

            DataFileDetails.PlayerFileExtension = Config.Default.PlayerFileExtension;
            DataFileDetails.TribeFileExtension  = Config.Default.TribeFileExtension;

            Task.Factory.StartNew(async() => await App.DiscoverMachinePublicIP(forceOverride: true));
        }
Пример #20
0
 /// <summary>
 /// Wykonuje komende wyjscia
 /// </summary>
 /// <param name="server">Instancja glownego obiektu aplikacji serwera</param>
 public void Execute(ServerApp server)
 {
     server.RequestExit();
 }
Пример #21
0
 public Form1()
 {
     InitializeComponent();
     _Server = new ServerApp();
 }
Пример #22
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            _globalizer = GlobalizedApplication.Instance;
            try
            {
                if (!string.IsNullOrWhiteSpace(Config.Default.CultureName))
                {
                    _globalizer.GlobalizationManager.SwitchLanguage(Config.Default.CultureName, true);
                }
            }
            catch (Exception ex)
            {
                // just output the exception message, it should default back to the fallback language.
                Debug.WriteLine(ex.Message);
            }

            try
            {
                if (!string.IsNullOrWhiteSpace(Config.Default.StyleName))
                {
                    _globalizer.StyleManager.SwitchStyle(Config.Default.StyleName, true);
                }
            }
            catch (Exception ex)
            {
                // just output the exception message, it should default back to the fallback style.
                Debug.WriteLine(ex.Message);
            }

            TaskSchedulerUtils.TaskFolder = Config.Default.ScheduledTaskFolder;

            this.Args = string.Join(" ", e.Args);

            // check if we are starting server manager in BETA/TEST mode
            if (e.Args.Any(a => a.Equals(Constants.ARG_BETA, StringComparison.OrdinalIgnoreCase) || a.Equals(Constants.ARG_TEST, StringComparison.OrdinalIgnoreCase)))
            {
                this.BetaVersion = true;
            }

            // check if we need to set the title
            if (e.Args.Any(a => a.Equals(Constants.ARG_TITLE, StringComparison.OrdinalIgnoreCase)))
            {
                for (int i = 0; i < e.Args.Length - 1; i++)
                {
                    if (e.Args[i].Equals(Constants.ARG_TITLE, StringComparison.OrdinalIgnoreCase) && i < e.Args.Length - 1 && !e.Args[i + 1].StartsWith("-"))
                    {
                        Title = e.Args[i + 1].Trim();
                    }
                }
            }

            // check and update the public IP address
            DiscoverMachinePublicIP(Config.Default.ManagePublicIPAutomatically);

            var installPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            PluginHelper.Instance.BetaEnabled = this.BetaVersion;
            PluginHelper.Instance.LoadPlugins(installPath, true);
            PluginHelper.Instance.SetFetchProfileCallback(FetchProfiles);

            // check if we are starting server manager for server shutdown
            if (e.Args.Any(a => a.StartsWith(Constants.ARG_AUTOSHUTDOWN1, StringComparison.OrdinalIgnoreCase)))
            {
                var arg      = e.Args.FirstOrDefault(a => a.StartsWith(Constants.ARG_AUTOSHUTDOWN1, StringComparison.OrdinalIgnoreCase));
                var exitCode = ServerApp.PerformAutoShutdown(arg, ServerProcessType.AutoShutdown1);

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            // check if we are starting server manager for server shutdown
            if (e.Args.Any(a => a.StartsWith(Constants.ARG_AUTOSHUTDOWN2, StringComparison.OrdinalIgnoreCase)))
            {
                var arg      = e.Args.FirstOrDefault(a => a.StartsWith(Constants.ARG_AUTOSHUTDOWN2, StringComparison.OrdinalIgnoreCase));
                var exitCode = ServerApp.PerformAutoShutdown(arg, ServerProcessType.AutoShutdown2);

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            // check if we are starting server manager for server updating
            if (e.Args.Any(a => a.Equals(Constants.ARG_AUTOUPDATE, StringComparison.OrdinalIgnoreCase)))
            {
                var exitCode = ServerApp.PerformAutoUpdate();

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            // check if we are starting server manager for server backups
            if (e.Args.Any(a => a.Equals(Constants.ARG_AUTOBACKUP, StringComparison.OrdinalIgnoreCase)))
            {
                var exitCode = ServerApp.PerformAutoBackup();

                // once we are finished, just exit
                Environment.Exit(exitCode);
            }

            if (Config.Default.RunAsAdministratorPrompt && !SecurityUtils.IsAdministrator())
            {
                var result = MessageBox.Show(_globalizer.GetResourceString("Application_RunAsAdministratorLabel"), _globalizer.GetResourceString("Application_RunAsAdministratorTitle"), MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    var processInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().CodeBase);

                    // The following properties run the new process as administrator
                    processInfo.UseShellExecute = true;
                    processInfo.Verb            = "runas";
                    processInfo.Arguments       = string.Join(" ", e.Args);

                    // Start the new process
                    try
                    {
                        Process.Start(processInfo);

                        // Shut down the current process
                        Application.Current.Shutdown(0);

                        return;
                    }
                    catch (Exception)
                    {
                        // The user did not allow the application to run as administrator
                        MessageBox.Show(_globalizer.GetResourceString("Application_RunAsAdministrator_FailedLabel"), _globalizer.GetResourceString("Application_RunAsAdministrator_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }

            // check if application is already running
            if (ProcessUtils.IsAlreadyRunning())
            {
                var result = MessageBox.Show(_globalizer.GetResourceString("Application_SingleInstanceLabel"), _globalizer.GetResourceString("Application_SingleInstanceTitle"), MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    if (ProcessUtils.SwitchToCurrentInstance())
                    {
                        // Shut down the current process
                        Application.Current.Shutdown(0);

                        return;
                    }

                    MessageBox.Show(_globalizer.GetResourceString("Application_SingleInstance_FailedLabel"), _globalizer.GetResourceString("Application_SingleInstance_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            this.ApplicationStarted = true;

            // Initial configuration setting
            if (String.IsNullOrWhiteSpace(Config.Default.DataPath))
            {
                MessageBox.Show(_globalizer.GetResourceString("Application_DataDirectoryLabel"), _globalizer.GetResourceString("Application_DataDirectoryTitle"), MessageBoxButton.OK, MessageBoxImage.Information);

                var installationFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                if (!installationFolder.EndsWith(@"\"))
                {
                    installationFolder += @"\";
                }

                while (String.IsNullOrWhiteSpace(Config.Default.DataPath))
                {
                    var dialog = new CommonOpenFileDialog
                    {
                        EnsureFileExists = true,
                        IsFolderPicker   = true,
                        Multiselect      = false,
                        Title            = _globalizer.GetResourceString("Application_DataDirectory_DialogTitle"),
                        InitialDirectory = installationFolder
                    };

                    if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                    {
                        Environment.Exit(0);
                    }

                    MessageBoxResult confirm = MessageBoxResult.Cancel;

                    // check if the folder is under the installation folder
                    var newDataFolder = dialog.FileName;
                    if (!newDataFolder.EndsWith(@"\"))
                    {
                        newDataFolder += @"\";
                    }

                    if (newDataFolder.StartsWith(installationFolder))
                    {
                        confirm = MessageBoxResult.No;
                        MessageBox.Show(_globalizer.GetResourceString("Application_DataDirectory_WithinInstallFolderErrorLabel"), _globalizer.GetResourceString("Application_DataDirectory_WithinInstallFolderErrorTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        confirm = MessageBox.Show(String.Format(_globalizer.GetResourceString("Application_DataDirectory_ConfirmLabel"), Path.Combine(newDataFolder, Config.Default.ProfilesRelativePath), Path.Combine(newDataFolder, CommonConfig.Default.SteamCmdRelativePath)), _globalizer.GetResourceString("Application_DataDirectory_ConfirmTitle"), MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                    }

                    if (confirm == MessageBoxResult.Cancel)
                    {
                        Environment.Exit(0);
                    }
                    else if (confirm == MessageBoxResult.Yes)
                    {
                        if (newDataFolder.EndsWith(@"\"))
                        {
                            newDataFolder = newDataFolder.Substring(0, newDataFolder.Length - 1);
                        }

                        Config.Default.DataPath = newDataFolder;
                        ReconfigureLogging();
                        break;
                    }
                }
            }

            Config.Default.ConfigPath = Path.Combine(Config.Default.DataPath, Config.Default.ProfilesRelativePath);
            System.IO.Directory.CreateDirectory(Config.Default.ConfigPath);
            Config.Default.Save();
            CommonConfig.Default.Save();

            if (e.Args.Any(a => a.StartsWith(Constants.ARG_SERVERMONITOR, StringComparison.OrdinalIgnoreCase)))
            {
                ServerRuntime.EnableUpdateModStatus    = false;
                ServerProfile.EnableServerFilesWatcher = false;

                StartupUri = new Uri("Windows/ServerMonitorWindow.xaml", UriKind.RelativeOrAbsolute);
            }
            else
            {
                // initialize all the game data
                GameData.Initialize();

                StartupUri = new Uri("Windows/AutoUpdateWindow.xaml", UriKind.RelativeOrAbsolute);
            }
        }
Пример #23
0
        private async Task StartServerAsync(Server server)
        {
            if (server == null || server.Profile == null || server.Runtime == null || server.Runtime.Status != ServerStatus.Stopped)
            {
                return;
            }

            Mutex mutex      = null;
            bool  createdNew = false;

            try
            {
                // try to establish a mutex for the profile.
                mutex = new Mutex(true, ServerApp.GetMutexName(server.Profile.InstallDirectory), out createdNew);

                // check if the mutex was established
                if (createdNew)
                {
                    server.Profile.Save(false, false, null);

                    if (!server.Profile.Validate(false, out string validateMessage))
                    {
                        var outputMessage = _globalizer.GetResourceString("ProfileValidation_WarningLabel").Replace("{validateMessage}", validateMessage);
                        if (MessageBox.Show(outputMessage, _globalizer.GetResourceString("ProfileValidation_Title"), MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
                        {
                            return;
                        }
                    }

                    await server.StartAsync();

                    var startupMessage = Config.Default.Alert_ServerStartedMessage;
                    if (Config.Default.Alert_ServerStartedMessageIncludeIPandPort)
                    {
                        startupMessage += $" {Config.Default.MachinePublicIP}:{server.Profile.QueryPort}";
                    }
                    PluginHelper.Instance.ProcessAlert(AlertType.Startup, server.Profile.ProfileName, startupMessage);

                    await Task.Delay(2000);
                }
                else
                {
                    // display an error message and exit
                    MessageBox.Show(_globalizer.GetResourceString("ServerSettings_StartServer_MutexFailedLabel"), _globalizer.GetResourceString("ServerSettings_StartServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_StartServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                if (mutex != null)
                {
                    if (createdNew)
                    {
                        mutex.ReleaseMutex();
                        mutex.Dispose();
                    }
                }
            }
        }
Пример #24
0
 public Consumer(IModel model, ServerApp <TContext> server) : base(model)
 {
     _server = server;
 }
        private async Task <bool> UpdateServerAsync(Server server, bool establishLock, bool updateServer, bool updateMods, bool closeProgressWindow)
        {
            if (server == null)
            {
                return(false);
            }

            if (_upgradeCancellationSource != null)
            {
                // display an error message and exit
                MessageBox.Show(_globalizer.GetResourceString("ServerMonitor_UpgradeServer_FailedLabel"), _globalizer.GetResourceString("ServerMonitor_UpgradeServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Information);
                return(false);
            }

            ProgressWindow window        = null;
            Mutex          mutex         = null;
            bool           createdNew    = !establishLock;
            var            serverProfile = server.Profile;

            try
            {
                if (establishLock)
                {
                    // try to establish a mutex for the profile.
                    mutex = new Mutex(true, ServerApp.GetMutexName(serverProfile.InstallDirectory), out createdNew);
                }

                // check if the mutex was established
                if (createdNew)
                {
                    _upgradeCancellationSource = new CancellationTokenSource();

                    window = new ProgressWindow(string.Format(_globalizer.GetResourceString("Progress_UpgradeServer_WindowTitle"), serverProfile.ProfileName))
                    {
                        Owner = Window.GetWindow(this)
                    };
                    window.Closed += Window_Closed;
                    window.Show();

                    await Task.Delay(1000);

                    var branch = new BranchSnapshot()
                    {
                        BranchName = serverProfile.BranchName, BranchPassword = serverProfile.BranchPassword
                    };
                    return(await server.UpgradeAsync(_upgradeCancellationSource.Token, updateServer, branch, true, updateMods, (p, m, n) => { TaskUtils.RunOnUIThreadAsync(() => { window?.AddMessage(m, n); }).DoNotWait(); }));
                }
                else
                {
                    // display an error message and exit
                    MessageBox.Show(_globalizer.GetResourceString("ServerSettings_UpgradeServer_MutexFailedLabel"), _globalizer.GetResourceString("ServerSettings_UpgradeServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Information);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                if (window != null)
                {
                    window.AddMessage(ex.Message);
                    window.AddMessage(ex.StackTrace);
                }
                MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_UpgradeServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }
            finally
            {
                _upgradeCancellationSource = null;

                if (window != null)
                {
                    window.CloseWindow();
                    if (closeProgressWindow)
                    {
                        window.Close();
                    }
                }

                if (mutex != null)
                {
                    if (createdNew)
                    {
                        mutex.ReleaseMutex();
                        mutex.Dispose();
                    }
                    mutex = null;
                }
            }
        }
        public async Task StartShutdownAsync()
        {
            if (ShutdownStarted)
            {
                return;
            }

            try
            {
                MessageOutput.Clear();

                ShutdownType = 1;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = System.Windows.Input.Cursors.Wait);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = System.Windows.Input.Cursors.Arrow);

                var app = new ServerApp(true)
                {
                    CheckForOnlinePlayers = this.CheckForOnlinePlayers,
                    SendMessages          = this.SendShutdownMessages,
                    BackupWorldFile       = this.BackupWorldFile,
                    ShutdownInterval      = this.ShutdownInterval,
                    ShutdownReason        = this.ShutdownReason,
                    OutputLogs            = false,
                    SendAlerts            = true,
                    ServerProcess         = RestartServer ? ServerProcessType.Restart : ServerProcessType.Shutdown,
                    ProgressCallback      = (p, m, n) => { TaskUtils.RunOnUIThreadAsync(() => { this.AddMessage(m, n); }).DoNotWait(); },
                };

                // if restarting the serverm, then check and update the public IP address
                if (RestartServer && Config.Default.ManagePublicIPAutomatically)
                {
                    await App.DiscoverMachinePublicIPAsync(false);
                }

                var profile       = ServerProfileSnapshot.Create(Server.Profile);
                var restartServer = RestartServer;
                var updateServer  = UpdateServer;

                _shutdownCancellationSource = new CancellationTokenSource();

                var exitCode = await Task.Run(() => app.PerformProfileShutdown(profile, restartServer, updateServer, false, _shutdownCancellationSource.Token));

                if (exitCode != ServerApp.EXITCODE_NORMALEXIT && exitCode != ServerApp.EXITCODE_CANCELLED)
                {
                    throw new ApplicationException($"An error occured during the shutdown process - ExitCode: {exitCode}");
                }

                if (restartServer)
                {
                    profile.Update(Server.Profile);
                    Server.Profile.SaveProfile();
                }

                ShutdownType = 0;
                // if restarting or updating the server after the shutdown, delay the form closing
                if (restartServer || updateServer)
                {
                    await Task.Delay(5000);
                }

                if (CloseShutdownWindowWhenFinished)
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_ShutdownServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                ShutdownType = 0;
            }
            finally
            {
                _shutdownCancellationSource = null;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = null);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = null);
            }
        }
Пример #27
0
        public async Task <bool> UpgradeAsync(CancellationToken cancellationToken, bool updateServer, bool validate, bool updateMods, ProgressDelegate progressCallback)
        {
            if (updateServer && !Environment.Is64BitOperatingSystem)
            {
                var result = MessageBox.Show("The ARK server requires a 64-bit operating system to run. Your operating system is 32-bit and therefore the Ark Server Manager will be unable to start the server, but you may still install it or load and save profiles and settings files for use on other machines.\r\n\r\nDo you wish to continue?", "64-bit OS Required", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (result == MessageBoxResult.No)
                {
                    return(false);
                }
            }

            try
            {
                await StopAsync();

                bool isNewInstallation = this.Status == ServerStatus.Uninstalled;

                this.Status = ServerStatus.Updating;

                // Run the SteamCMD to install the server
                var steamCmdFile = Updater.GetSteamCmdFile();
                if (string.IsNullOrWhiteSpace(steamCmdFile) || !File.Exists(steamCmdFile))
                {
                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***********************************");
                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: SteamCMD could not be found. Expected location is {steamCmdFile}");
                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***********************************");
                    return(false);
                }

                // record the start time of the process, this is used to determine if any files changed in the download process.
                var startTime = DateTime.Now;

                var gotNewVersion      = false;
                var downloadSuccessful = false;
                var success            = false;

                if (updateServer)
                {
                    // *********************
                    // Server Update Section
                    // *********************

                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Starting server update.");

                    // Check if this is a new server installation.
                    if (isNewInstallation)
                    {
                        // check if the auto-update facility is enabled and the cache folder defined.
                        if (!this.ProfileSnapshot.SotFServer && Config.Default.AutoUpdate_EnableUpdate && !string.IsNullOrWhiteSpace(Config.Default.AutoUpdate_CacheDir) && Directory.Exists(Config.Default.AutoUpdate_CacheDir))
                        {
                            // Auto-Update enabled and cache foldler exists.
                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Installing server from local cache...may take a while to copy all the files.");

                            // Install the server files from the cache.
                            var installationFolder = this.ProfileSnapshot.InstallDirectory;
                            int count = 0;
                            await Task.Run(() =>
                                           ServerApp.DirectoryCopy(Config.Default.AutoUpdate_CacheDir, installationFolder, true, Config.Default.AutoUpdate_UseSmartCopy, (p, m, n) =>
                            {
                                count++;
                                progressCallback?.Invoke(0, ".", count % DIRECTORIES_PER_LINE == 0);
                            }), cancellationToken);
                        }
                    }

                    progressCallback?.Invoke(0, "\r\n");
                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Updating server from steam.\r\n");

                    downloadSuccessful = !Config.Default.SteamCmdRedirectOutput;
                    DataReceivedEventHandler serverOutputHandler = (s, e) =>
                    {
                        var dataValue = e.Data ?? string.Empty;
                        progressCallback?.Invoke(0, dataValue);
                        if (!gotNewVersion && dataValue.Contains("downloading,"))
                        {
                            gotNewVersion = true;
                        }
                        if (dataValue.StartsWith("Success!"))
                        {
                            downloadSuccessful = true;
                        }
                    };

                    var steamCmdInstallServerArgsFormat = this.ProfileSnapshot.SotFServer ? Config.Default.SteamCmdInstallServerArgsFormat_SotF : Config.Default.SteamCmdInstallServerArgsFormat;
                    var steamCmdArgs = String.Format(steamCmdInstallServerArgsFormat, this.ProfileSnapshot.InstallDirectory, validate ? "validate" : string.Empty);

                    success = await ServerUpdater.UpgradeServerAsync(steamCmdFile, steamCmdArgs, this.ProfileSnapshot.InstallDirectory, Config.Default.SteamCmdRedirectOutput?serverOutputHandler : null, cancellationToken);

                    if (success && downloadSuccessful)
                    {
                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Finished server update.");

                        if (Directory.Exists(this.ProfileSnapshot.InstallDirectory))
                        {
                            if (!Config.Default.SteamCmdRedirectOutput)
                            {
                                // check if any of the server files have changed.
                                gotNewVersion = ServerApp.HasNewServerVersion(this.ProfileSnapshot.InstallDirectory, startTime);
                            }

                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} New server version - {gotNewVersion.ToString().ToUpperInvariant()}.");
                        }

                        progressCallback?.Invoke(0, "\r\n");
                    }
                    else
                    {
                        success = false;
                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ****************************");
                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: Failed server update.");
                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ****************************\r\n");

                        if (Config.Default.SteamCmdRedirectOutput)
                        {
                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} If the server update keeps failing try disabling the '{_globalizer.GetResourceString("GlobalSettings_SteamCmdRedirectOutputLabel")}' option in the settings window.\r\n");
                        }
                    }
                }
                else
                {
                    success = true;
                }

                if (success)
                {
                    if (updateMods)
                    {
                        // ******************
                        // Mod Update Section
                        // ******************

                        // build a list of mods to be processed
                        var modIdList = new List <string>();
                        if (!string.IsNullOrWhiteSpace(this.ProfileSnapshot.ServerMapModId))
                        {
                            modIdList.Add(this.ProfileSnapshot.ServerMapModId);
                        }
                        if (!string.IsNullOrWhiteSpace(this.ProfileSnapshot.TotalConversionModId))
                        {
                            modIdList.Add(this.ProfileSnapshot.TotalConversionModId);
                        }
                        modIdList.AddRange(this.ProfileSnapshot.ServerModIds);

                        modIdList = ModUtils.ValidateModList(modIdList);

                        // get the details of the mods to be processed.
                        var modDetails = SteamUtils.GetSteamModDetails(modIdList);
                        if (modDetails != null)
                        {
                            // create a new list for any failed mod updates
                            var failedMods = new List <string>(modIdList.Count);

                            for (var index = 0; index < modIdList.Count; index++)
                            {
                                var modId      = modIdList[index];
                                var modTitle   = modId;
                                var modSuccess = false;
                                gotNewVersion      = false;
                                downloadSuccessful = false;

                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Started processing mod {index + 1} of {modIdList.Count}.");
                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Mod {modId}.");

                                // check if the steam information was downloaded
                                var modDetail = modDetails.publishedfiledetails?.FirstOrDefault(m => m.publishedfileid.Equals(modId, StringComparison.OrdinalIgnoreCase));
                                if (modDetail != null)
                                {
                                    modTitle = $"{modDetail.title} ({modId})";
                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} {modDetail.title ?? string.Empty}.\r\n");

                                    var modCachePath  = ModUtils.GetModCachePath(modId, this.ProfileSnapshot.SotFServer);
                                    var cacheTimeFile = ModUtils.GetLatestModCacheTimeFile(modId, this.ProfileSnapshot.SotFServer);
                                    var modPath       = ModUtils.GetModPath(this.ProfileSnapshot.InstallDirectory, modId);
                                    var modTimeFile   = ModUtils.GetLatestModTimeFile(this.ProfileSnapshot.InstallDirectory, modId);

                                    var modCacheLastUpdated = 0;
                                    var downloadMod         = true;
                                    var copyMod             = true;

                                    if (downloadMod)
                                    {
                                        // check if the mod needs to be downloaded, or force the download.
                                        if (Config.Default.ServerUpdate_ForceUpdateMods)
                                        {
                                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Forcing mod download - ASM setting is TRUE.");
                                        }
                                        else
                                        {
                                            // check if the mod detail record is valid (private mod).
                                            if (modDetail.time_updated <= 0)
                                            {
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Forcing mod download - mod is private.");
                                            }
                                            else
                                            {
                                                modCacheLastUpdated = ModUtils.GetModLatestTime(cacheTimeFile);
                                                if (modCacheLastUpdated <= 0)
                                                {
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Forcing mod download - mod cache is not versioned.");
                                                }
                                                else
                                                {
                                                    var steamLastUpdated = modDetail.time_updated;
                                                    if (steamLastUpdated <= modCacheLastUpdated)
                                                    {
                                                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Skipping mod download - mod cache has the latest version.");
                                                        downloadMod = false;
                                                    }
                                                }
                                            }
                                        }

                                        if (downloadMod)
                                        {
                                            // mod will be downloaded
                                            downloadSuccessful = !Config.Default.SteamCmdRedirectOutput;
                                            DataReceivedEventHandler modOutputHandler = (s, e) =>
                                            {
                                                var dataValue = e.Data ?? string.Empty;
                                                progressCallback?.Invoke(0, dataValue);
                                                if (dataValue.StartsWith("Success."))
                                                {
                                                    downloadSuccessful = true;
                                                }
                                            };

                                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Starting mod download.\r\n");

                                            var steamCmdArgs = string.Empty;
                                            if (this.ProfileSnapshot.SotFServer)
                                            {
                                                if (Config.Default.SteamCmd_UseAnonymousCredentials)
                                                {
                                                    steamCmdArgs = string.Format(Config.Default.SteamCmdInstallModArgsFormat_SotF, Config.Default.SteamCmd_AnonymousUsername, modId);
                                                }
                                                else
                                                {
                                                    steamCmdArgs = string.Format(Config.Default.SteamCmdInstallModArgsFormat_SotF, Config.Default.SteamCmd_Username, modId);
                                                }
                                            }
                                            else
                                            {
                                                if (Config.Default.SteamCmd_UseAnonymousCredentials)
                                                {
                                                    steamCmdArgs = string.Format(Config.Default.SteamCmdInstallModArgsFormat, Config.Default.SteamCmd_AnonymousUsername, modId);
                                                }
                                                else
                                                {
                                                    steamCmdArgs = string.Format(Config.Default.SteamCmdInstallModArgsFormat, Config.Default.SteamCmd_Username, modId);
                                                }
                                            }

                                            modSuccess = await ServerUpdater.UpgradeModsAsync(steamCmdFile, steamCmdArgs, Config.Default.SteamCmdRedirectOutput?modOutputHandler : null, cancellationToken);

                                            if (modSuccess && downloadSuccessful)
                                            {
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Finished mod download.");
                                                copyMod = true;

                                                if (Directory.Exists(modCachePath))
                                                {
                                                    // check if any of the mod files have changed.
                                                    gotNewVersion = new DirectoryInfo(modCachePath).GetFiles("*.*", SearchOption.AllDirectories).Any(file => file.LastWriteTime >= startTime);

                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} New mod version - {gotNewVersion.ToString().ToUpperInvariant()}.");

                                                    var steamLastUpdated = modDetail.time_updated.ToString();
                                                    if (modDetail.time_updated <= 0)
                                                    {
                                                        // get the version number from the steamcmd workshop file.
                                                        steamLastUpdated = ModUtils.GetSteamWorkshopLatestTime(ModUtils.GetSteamWorkshopFile(this.ProfileSnapshot.SotFServer), modId).ToString();
                                                    }

                                                    // update the last updated file with the steam updated time.
                                                    File.WriteAllText(cacheTimeFile, steamLastUpdated);

                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Mod Cache version: {steamLastUpdated}\r\n");
                                                }
                                            }
                                            else
                                            {
                                                modSuccess = false;
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***************************");
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: Mod download failed.");
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***************************\r\n");

                                                if (Config.Default.SteamCmdRedirectOutput)
                                                {
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} If the mod update keeps failing try disabling the '{_globalizer.GetResourceString("GlobalSettings_SteamCmdRedirectOutputLabel")}' option in the settings window.\r\n");
                                                }
                                                copyMod = false;
                                            }
                                        }
                                        else
                                        {
                                            modSuccess = true;
                                        }
                                    }
                                    else
                                    {
                                        modSuccess = true;
                                    }

                                    if (copyMod)
                                    {
                                        // check if the mod needs to be copied, or force the copy.
                                        if (Config.Default.ServerUpdate_ForceCopyMods)
                                        {
                                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Forcing mod copy - ASM setting is TRUE.");
                                        }
                                        else
                                        {
                                            // check the mod version against the cache version.
                                            var modLastUpdated = ModUtils.GetModLatestTime(modTimeFile);
                                            if (modLastUpdated <= 0)
                                            {
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Forcing mod copy - mod is not versioned.");
                                            }
                                            else
                                            {
                                                modCacheLastUpdated = ModUtils.GetModLatestTime(cacheTimeFile);
                                                if (modCacheLastUpdated <= modLastUpdated)
                                                {
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Skipping mod copy - mod has the latest version.");
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Mod version: {modLastUpdated}");
                                                    copyMod = false;
                                                }
                                            }
                                        }

                                        if (copyMod)
                                        {
                                            try
                                            {
                                                if (Directory.Exists(modCachePath))
                                                {
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Started mod copy.");
                                                    int count = 0;
                                                    await Task.Run(() => ModUtils.CopyMod(modCachePath, modPath, modId, (p, m, n) =>
                                                    {
                                                        count++;
                                                        progressCallback?.Invoke(0, ".", count % DIRECTORIES_PER_LINE == 0);
                                                    }), cancellationToken);

                                                    progressCallback?.Invoke(0, "\r\n");
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Finished mod copy.");

                                                    var modLastUpdated = ModUtils.GetModLatestTime(modTimeFile);
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Mod version: {modLastUpdated}");
                                                }
                                                else
                                                {
                                                    modSuccess = false;
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ****************************************************");
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: Mod cache was not found, mod was not updated.");
                                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ****************************************************");
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                modSuccess = false;
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***********************");
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: Failed mod copy.\r\n{ex.Message}");
                                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***********************");
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    // no steam information downloaded, display an error, mod might no longer be available
                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} *******************************************************************");
                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: Mod cannot be updated, unable to download steam information.");
                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} *******************************************************************");
                                }

                                if (!modSuccess)
                                {
                                    success = false;
                                    failedMods.Add($"{index + 1} of {modIdList.Count} - {modTitle}");
                                }

                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Finished processing mod {modId}.\r\n");
                            }

                            if (failedMods.Count > 0)
                            {
                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} **************************************************************************");
                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: The following mods failed the update, check above for more details.");
                                foreach (var failedMod in failedMods)
                                {
                                    progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} {failedMod}");
                                }
                                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} **************************************************************************\r\n");
                            }
                        }
                        else
                        {
                            success = false;
                            // no steam information downloaded, display an error
                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ********************************************************************");
                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: Mods cannot be updated, unable to download steam information.");
                            progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ********************************************************************\r\n");
                        }
                    }
                }
                else
                {
                    if (updateServer && updateMods)
                    {
                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***********************************************************");
                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ERROR: Mods were not processed as server update had errors.");
                        progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} ***********************************************************\r\n");
                    }
                }

                progressCallback?.Invoke(0, $"{Updater.OUTPUT_PREFIX} Finished upgrade process.");
                return(success);
            }
            catch (TaskCanceledException)
            {
                return(false);
            }
            finally
            {
                this.Status = ServerStatus.Stopped;
            }
        }
Пример #28
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Unicode;
            Console.Title          = "Grand Cheese Game";

            Console.WriteLine("  ////////////////////////////////////////");
            Console.WriteLine("         Grand Cheese Season V / Game     ");
            Console.WriteLine("  ////////////////////////////////////////");
            Console.WriteLine();

            Lua.RunLuaScript("Config");

            using (var db = Database.Get())
            {
                var server = db.Query <KServerInfo>("SELECT * FROM servers WHERE port = @port",
                                                    new { port = Lua.GetLuaGlobal("port").CastToNumber() }).FirstOrDefault();

                if (server != null)
                {
                    Info = server;
                }
            }

            var serverApp = new ServerApp
            {
                CreateUserClient = (Client c) =>
                {
                    c.User = new UserClient(c);
                },

                CustomInvoke = (ServerApp app, Client c, Packet p, short opcode) =>
                {
                    if (c.User == null)
                    {
                        c.User = new UserClient(c);
                    }

                    var user   = (UserClient)c.User;
                    var method = app.serverPackets[opcode];

                    var invocationArgs = new List <object>();

                    foreach (var param in method.GetParameters())
                    {
                        if (param.ParameterType == typeof(Client))
                        {
                            invocationArgs.Add(c);
                        }
                        else if (param.ParameterType == typeof(Packet))
                        {
                            invocationArgs.Add(p);
                        }
                        else if (param.ParameterType == typeof(KUser))
                        {
                            invocationArgs.Add(user.KUser);
                        }
                    }

                    switch (method.DeclaringType.Name)
                    {
                    case "KUser":
                        method.Invoke(user.KUser, invocationArgs.ToArray());
                        break;

                    default:
                        try
                        {
                            method.Invoke(null, invocationArgs.ToArray());
                        }
                        catch (TargetInvocationException ex)
                        {
                            Log.Get().Error(ex, "Unhandled packet. Failed to call as static.");
                        }
                        break;
                    }
                }
            };

            serverApp.StartServer(Info.Port, "game");

            Lua.RunLuaScript("CharDefaultInfo");

            if (serverApp.initialized)
            {
                // Delay the loading of the shell just in case...
                System.Threading.Thread.Sleep(2500);

                // Start the Lua shell
                Console.WriteLine();
                Console.WriteLine(GetLuaInfo());

                //var script = new Script();

                while (true)
                {
                    Console.Write("> ");
                    var input = Console.ReadLine();

                    if (input == "exit")
                    {
                        Environment.Exit(0);
                    }

                    try
                    {
                        Console.WriteLine(Lua.script.DoString(input).CastToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Get().Fatal(ex.Message);
                    }
                }
            }
        }
        private async Task StartStopServerAsync(Server server)
        {
            if (server == null)
            {
                return;
            }

            var serverRuntime       = server.Runtime;
            var serverProfile       = server.Profile;
            MessageBoxResult result = MessageBoxResult.None;

            switch (serverRuntime.Status)
            {
            case ServerStatus.Initializing:
            case ServerStatus.Running:
                // check if the server is initialising.
                if (serverRuntime.Status == ServerStatus.Initializing)
                {
                    result = MessageBox.Show(_globalizer.GetResourceString("ServerSettings_StartServer_StartingLabel"), _globalizer.GetResourceString("ServerSettings_StartServer_StartingTitle"), MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.No)
                    {
                        return;
                    }

                    try
                    {
                        PluginHelper.Instance.ProcessAlert(AlertType.Shutdown, serverProfile.ProfileName, Config.Default.Alert_ServerStopMessage);
                        await Task.Delay(2000);

                        await server.StopAsync();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_StopServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    try
                    {
                        var shutdownWindow = ShutdownWindow.OpenShutdownWindow(server);
                        if (shutdownWindow == null)
                        {
                            MessageBox.Show(_globalizer.GetResourceString("ServerSettings_ShutdownServer_AlreadyOpenLabel"), _globalizer.GetResourceString("ServerSettings_ShutdownServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }

                        shutdownWindow.Owner   = Window.GetWindow(this);
                        shutdownWindow.Closed += Window_Closed;
                        shutdownWindow.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_ShutdownServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                break;

            case ServerStatus.Stopped:
                Mutex mutex      = null;
                bool  createdNew = false;

                try
                {
                    // try to establish a mutex for the profile.
                    mutex = new Mutex(true, ServerApp.GetMutexName(serverProfile.InstallDirectory), out createdNew);

                    // check if the mutex was established
                    if (createdNew)
                    {
                        serverProfile.Save(false, false, null);

                        if (Config.Default.ServerUpdate_OnServerStart)
                        {
                            if (!await UpdateServerAsync(server, false, true, Config.Default.ServerUpdate_UpdateModsWhenUpdatingServer, true))
                            {
                                if (MessageBox.Show(_globalizer.GetResourceString("ServerUpdate_WarningLabel"), _globalizer.GetResourceString("ServerUpdate_Title"), MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
                                {
                                    return;
                                }
                            }
                        }

                        if (!serverProfile.Validate(false, out string validateMessage))
                        {
                            var outputMessage = _globalizer.GetResourceString("ProfileValidation_WarningLabel").Replace("{validateMessage}", validateMessage);
                            if (MessageBox.Show(outputMessage, _globalizer.GetResourceString("ProfileValidation_Title"), MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
                            {
                                return;
                            }
                        }

                        await server.StartAsync();

                        var startupMessage = Config.Default.Alert_ServerStartedMessage;
                        if (Config.Default.Alert_ServerStartedMessageIncludeIPandPort)
                        {
                            startupMessage += $" {Config.Default.MachinePublicIP}:{serverProfile.QueryPort}";
                        }
                        PluginHelper.Instance.ProcessAlert(AlertType.Startup, serverProfile.ProfileName, startupMessage);

                        await Task.Delay(2000);
                    }
                    else
                    {
                        // display an error message and exit
                        MessageBox.Show(_globalizer.GetResourceString("ServerSettings_StartServer_MutexFailedLabel"), _globalizer.GetResourceString("ServerSettings_StartServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_StartServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    if (mutex != null)
                    {
                        if (createdNew)
                        {
                            mutex.ReleaseMutex();
                            mutex.Dispose();
                        }
                        mutex = null;
                    }
                }
                break;
            }
        }
Пример #30
0
        void StartRdpCapturePlay(object data)
        {
            var resp = (string)data;

            // Transmit resulting JSON to Packager
            var rdpAuthJsonFile = System.IO.Path.GetTempFileName();
            var rdpAuth = ServerClient.DeserializeJson<RdpAuthData>(resp);
            if (rdpAuth == null)
            {
                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                {
                    DisplayError("Failed starting session.");
                }));
                return;
            }
            string rdpTokenId = rdpAuth.parameters.rdp_token;
            File.WriteAllText(rdpAuthJsonFile, resp);   // Transmit to Packager, he'll know what to do with it...

            // Start Play session
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
            {
                borderMain.Opacity = 0.3;
                var serverApp = new ServerApp() { PkgId = rdpAuthJsonFile };
                var appDisplay = new AppDisplay(serverApp);
                var playing = new Playing(appDisplay, Playing.AppAction.Play, null);
                playing.Owner = this;
                playing.ShowDialog();
                borderMain.Opacity = 1;
            }));

            // Wait for resulting package or failure
            var thread = new Thread(new ParameterizedThreadStart(WaitForRdpCapturePkg));
            thread.Start(rdpTokenId);
            //WaitForRdpCapturePkg(rdpTokenId);
            //Close();
        }
Пример #31
0
 public void Execute(NebulaUser user, params string[] args)
 {
     ServerApp.Clear();
 }