public MainAboutModel(RootModel root, ConnectionService connectionService, IAppEnvironment environment, IdService idService, CoreData coreData)
        {
            Root = root;
            _connectionService = connectionService;
            _environment       = environment;
            _idService         = idService;
            _coreData          = coreData;
            CopyToClipboard    = () => DoCopyToClipboard();

            Version = ClientVersionHelper.GetVersion();

            var assembly = Assembly.GetExecutingAssembly();

            using (Stream stream = assembly.GetManifestResourceStream("Streamster.ClientCore.LICENSE.txt"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    License = reader.ReadToEnd();
                }

            using (Stream stream = assembly.GetManifestResourceStream("Streamster.ClientCore.CREDITS.txt"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    Credits = reader.ReadToEnd();
                }

            FeedbackSend = () => _ = SendFeedback();
        }
Exemplo n.º 2
0
        public LoginModel(RootModel root, MainModel main, UpdateModel updateModel,
                          LocalSettingsService settingsService,
                          ConnectionService connectionService,
                          NotificationService notificationService,
                          IAppEnvironment environment,
                          IdService idService)
        {
            Root = root;

            _settingsService     = settingsService;
            _connectionService   = connectionService;
            _notificationService = notificationService;
            _main        = main;
            _updateModel = updateModel;
            _environment = environment;
            _idService   = idService;
            var s = settingsService.Settings;

            SavePassword   = s.SavePassword;
            UserName       = s.UserName;
            Password       = s.Password;
            UserRegistered = s.UserRegistered;

            Version = ClientVersionHelper.GetVersion();

            DoLogin = async() => await LoginAsync(true);

            DoAnonymousLogin = async() => await LoginAsync(false);

            if (s.AutoLogon && s.SavePassword && s.UserRegistered)
            {
                _ = DoAutoLogin();
            }
        }
        public void Start()
        {
            AsUnregistered.Value = _connectionService.UserName == null;

            try
            {
                _environment.GetObsVersions(out var obs, out var obsCam);
                SystemInfos.Value = new[]
                {
                    new SystemInfoItem {
                        Name = "Logged as", Value = _connectionService.UserName ?? "Unregistered"
                    },
                    new SystemInfoItem {
                        Name = "Processor", Value = _environment.GetProcessorName()
                    },
                    new SystemInfoItem {
                        Name = "Device Id", Value = _idService.GetDeviceId()
                    },
                    new SystemInfoItem {
                        Name = "OS", Value = System.Runtime.InteropServices.RuntimeInformation.OSDescription
                    },
                    new SystemInfoItem {
                        Name = "Start time UTC", Value = DateTime.UtcNow.ToString()
                    },
                    new SystemInfoItem {
                        Name = "Server", Value = _connectionService.ConnectionServer.Split(':')[0]
                    },
                    new SystemInfoItem {
                        Name = "App version", Value = ClientVersionHelper.GetVersion()
                    },
                    new SystemInfoItem {
                        Name = "OBS version", Value = obs
                    },
                    new SystemInfoItem {
                        Name = "OBS Cam version", Value = obsCam
                    }
                }.Where(s => s.Value != null).ToArray();

                SystemInfos.Value.Where(s => s.Id != null).ToList().ForEach(s => Log.Information($"SystemInfo {{{s.Id}}}", s.Value));
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to get system info");
            }
        }
Exemplo n.º 4
0
        private void ProcessNewVersion(ClientVersion[] upperVersions)
        {
            var(currentVersionInfo, currentVersionString) = ClientVersionHelper.GetCurrent(upperVersions);

            bool   simulateUpdate = false;
            string custom         = "4.5.0";

            if (_localSettingsService.Settings.LastRunVerion != currentVersionString || simulateUpdate)
            {
                if ((_localSettingsService.Settings.NotFirstInstall || _localSettingsService.NoSettingsFileAtLoad == false) &&
                    string.IsNullOrEmpty(_appResources.AppData.Domain) || simulateUpdate)
                {
                    string[] standard = string.IsNullOrWhiteSpace(currentVersionInfo?.WhatsNew) ? null :
                                        currentVersionInfo.WhatsNew.Split(';').Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => "\u2022 " + s.Trim()).ToArray();

                    if (standard != null || currentVersionString == custom)
                    {
                        NewVersionModel newVersion = new NewVersionModel
                        {
                            WhatsNew   = standard,
                            Title      = $"You are running new version {currentVersionString}",
                            CustomView = !string.IsNullOrWhiteSpace(custom)
                        };

                        if (DialogContent.Value == null)
                        {
                            DialogContent.Value = newVersion;
                            IsDialogShown.Value = true;
                        }
                    }
                }

                TaskHelper.RunUnawaited(_localSettingsService.ChangeSettingsUnconditionally(s =>
                {
                    s.LastRunVerion   = currentVersionString;
                    s.NotFirstInstall = true;
                }), "Store LastRunVerion");
            }
        }
Exemplo n.º 5
0
        public LogService(IAppEnvironment environment, Func <HubConnectionService> hubConnectionServiceFactory)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(_switch)
#if DEBUG
                         //.WriteTo.Async(a =>
                         //{
                         //    a.Debug(outputTemplate: "[{Timestamp:dd HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}");
                         //})
#endif
                         .WriteTo.File(path: $"{environment.GetStorageFolder()}\\Logs\\Client.txt",
                                       fileSizeLimitBytes: 10_000_000,
                                       retainedFileCountLimit: 2,
                                       rollOnFileSizeLimit: true,
                                       //                flushToDiskInterval: TimeSpan.Zero,
                                       outputTemplate: "[{Timestamp:dd HH:mm:ss.fff}] {Level:u3}]: {Message:lj}{NewLine}{Exception}")
                         .WriteTo.ServerLog(hubConnectionServiceFactory)
                         .CreateLogger();

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Log.Information($"Application started '{ClientVersionHelper.GetVersion()}'");
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            // - check for update
            // - launcher & user setup
            // - game setup
            // - game launch
            // - enjoy

            CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

            Log.Start(LogTypes.All);

            CUOEnviroment.GameThread      = Thread.CurrentThread;
            CUOEnviroment.GameThread.Name = "CUO_MAIN_THREAD";


#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("######################## [START LOG] ########################");

#if DEV_BUILD
                sb.AppendLine($"ClassicUO [DEV_BUILD] - {CUOEnviroment.Version}");
#else
                sb.AppendLine($"ClassicUO [STANDARD_BUILD] - {CUOEnviroment.Version}");
#endif

                sb.AppendLine($"OS: {Environment.OSVersion.Platform} x{(Environment.Is64BitOperatingSystem ? "64" : "86")}");
                sb.AppendLine($"Thread: {Thread.CurrentThread.Name}");
                sb.AppendLine();

                sb.AppendLine($"Protocol: {Client.Protocol}");
                sb.AppendLine($"ClientFeatures: {World.ClientFeatures.Flags}");
                sb.AppendLine($"ClientLockedFeatures: {World.ClientLockedFeatures.Flags}");
                sb.AppendLine($"ClientVersion: {Client.Version}");

                sb.AppendLine();
                sb.AppendFormat("Exception:\n{0}\n", e.ExceptionObject);
                sb.AppendLine("######################## [END LOG] ########################");
                sb.AppendLine();
                sb.AppendLine();

                Log.Panic(e.ExceptionObject.ToString());
                string path = Path.Combine(CUOEnviroment.ExecutablePath, "Logs");

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                using (LogFile crashfile = new LogFile(path, "crash.txt"))
                {
                    crashfile.WriteAsync(sb.ToString()).RunSynchronously();
                }
            };
#endif
            ReadSettingsFromArgs(args);

#if DEV_BUILD
            if (!_skipUpdates)
            {
                Updater updater = new Updater();
                if (updater.Check())
                {
                    return;
                }
            }
#endif

            if (!_skipUpdates)
            {
                if (CheckUpdate(args))
                {
                    return;
                }
            }

            if (CUOEnviroment.IsHighDPI)
            {
                Log.Trace("HIGH DPI - ENABLED");
                Environment.SetEnvironmentVariable("FNA_GRAPHICS_ENABLE_HIGHDPI", "1");
            }
            Environment.SetEnvironmentVariable("FNA3D_BACKBUFFER_SCALE_NEAREST", "1");
            Environment.SetEnvironmentVariable("FNA3D_OPENGL_FORCE_COMPATIBILITY_PROFILE", "1");
            Environment.SetEnvironmentVariable(SDL.SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
            Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Plugins"));


            string globalSettingsPath = Settings.GetSettingsFilepath();

            if ((!Directory.Exists(Path.GetDirectoryName(globalSettingsPath)) ||
                 !File.Exists(globalSettingsPath)))
            {
                // settings specified in path does not exists, make new one
                {
                    // TODO:
                    Settings.GlobalSettings.Save();
                }
            }

            Settings.GlobalSettings  = ConfigurationResolver.Load <Settings>(globalSettingsPath);
            CUOEnviroment.IsOutlands = Settings.GlobalSettings.ShardType == 2;

            ReadSettingsFromArgs(args);

            // still invalid, cannot load settings
            if (Settings.GlobalSettings == null)
            {
                Settings.GlobalSettings = new Settings();
                Settings.GlobalSettings.Save();
            }

            if (!CUOEnviroment.IsUnix)
            {
                string libsPath = Path.Combine(CUOEnviroment.ExecutablePath, Environment.Is64BitProcess ? "x64" : "x86");
                SetDllDirectory(libsPath);
            }

            // FIXME: force to use OpenGL in osx and linux contexts. Metal wants texture converted in .Color instead of BGRA5551.
            //        Check the branch "fna3d-macos-fix"

            /*if (CUOEnviroment.IsUnix)
             * {
             *  Environment.SetEnvironmentVariable("FNA3D_FORCE_DRIVER", "OpenGL");
             * }
             */

            if (string.IsNullOrWhiteSpace(Settings.GlobalSettings.UltimaOnlineDirectory))
            {
                Settings.GlobalSettings.UltimaOnlineDirectory = CUOEnviroment.ExecutablePath;
            }


            const uint INVALID_UO_DIRECTORY = 0x100;
            const uint INVALID_UO_VERSION   = 0x200;

            uint flags = 0;


            if (!Directory.Exists(Settings.GlobalSettings.UltimaOnlineDirectory) || !File.Exists(UOFileManager.GetUOFilePath("tiledata.mul")))
            {
                flags |= INVALID_UO_DIRECTORY;
            }


            string clientVersionText = Settings.GlobalSettings.ClientVersion;

            if (!ClientVersionHelper.IsClientVersionValid(Settings.GlobalSettings.ClientVersion, out var clientVersion))
            {
                Log.Warn($"Client version [{clientVersionText}] is invalid, let's try to read the client.exe");

                // mmm something bad happened, try to load from client.exe [windows only]
                if (!ClientVersionHelper.TryParseFromFile(Path.Combine(Settings.GlobalSettings.UltimaOnlineDirectory, "client.exe"), out clientVersionText) ||
                    !ClientVersionHelper.IsClientVersionValid(clientVersionText, out clientVersion))
                {
                    Log.Error("Invalid client version: " + clientVersionText);

                    flags |= INVALID_UO_VERSION;
                }
                else
                {
                    Log.Trace($"Found a valid client.exe [{clientVersionText} - {clientVersion}]");

                    // update the wrong/missing client version in settings.json
                    Settings.GlobalSettings.ClientVersion = clientVersionText;
                }
            }


            if (flags != 0)
            {
                if ((flags & INVALID_UO_DIRECTORY) != 0)
                {
                    Client.ShowErrorMessage("Your Ultima Online directory seems to be invalid.\nDownload the official Launcher to setup and run your game.\n\nLink: classicuo.eu");
                }
                else if ((flags & INVALID_UO_VERSION) != 0)
                {
                    Client.ShowErrorMessage("Your Ultima Online client version seems to be invalid.\nDownload the official Launcher to setup and run your game.\n\nLink: classicuo.eu");
                }

                try
                {
                    Process.Start("https://classicuo.eu");
                }
                catch { }
            }
            else
            {
                switch (Settings.GlobalSettings.ForceDriver)
                {
                case 1:     // OpenGL
                    Environment.SetEnvironmentVariable("FNA3D_FORCE_DRIVER", "OpenGL");

                    break;

                case 2:     // Vulkan
                    Environment.SetEnvironmentVariable("FNA3D_FORCE_DRIVER", "Vulkan");

                    break;
                }

                Client.Run();
            }


            Log.Trace("Closing...");
        }
Exemplo n.º 7
0
        public static void Load()
        {
            Log.Trace(">>>>>>>>>>>>> Loading >>>>>>>>>>>>>");

            string clientPath = Settings.GlobalSettings.UltimaOnlineDirectory;

            Log.Trace($"Ultima Online installation folder: {clientPath}");

            Log.Trace("Loading files...");

            if (!string.IsNullOrWhiteSpace(Settings.GlobalSettings.ClientVersion))
            {
                // sanitize client version
                Settings.GlobalSettings.ClientVersion = Settings.GlobalSettings.ClientVersion.Replace(",", ".").Replace(" ", "").ToLower();
            }

            string clientVersionText = Settings.GlobalSettings.ClientVersion;

            // check if directory is good
            if (!Directory.Exists(clientPath))
            {
                Log.Error("Invalid client directory: " + clientPath);
                ShowErrorMessage($"'{clientPath}' is not a valid UO directory");
                throw new InvalidClientDirectory($"'{clientPath}' is not a valid directory");
            }

            // try to load the client version
            if (!ClientVersionHelper.IsClientVersionValid(clientVersionText, out ClientVersion clientVersion))
            {
                Log.Warn($"Client version [{clientVersionText}] is invalid, let's try to read the client.exe");

                // mmm something bad happened, try to load from client.exe
                if (!ClientVersionHelper.TryParseFromFile(Path.Combine(clientPath, "client.exe"), out clientVersionText) ||
                    !ClientVersionHelper.IsClientVersionValid(clientVersionText, out clientVersion))
                {
                    Log.Error("Invalid client version: " + clientVersionText);
                    ShowErrorMessage($"Impossible to define the client version.\nClient version: '{clientVersionText}'");
                    throw new InvalidClientVersion($"Invalid client version: '{clientVersionText}'");
                }

                Log.Trace($"Found a valid client.exe [{clientVersionText} - {clientVersion}]");

                // update the wrong/missing client version in settings.json
                Settings.GlobalSettings.ClientVersion = clientVersionText;
            }

            Version           = clientVersion;
            ClientPath        = clientPath;
            IsUOPInstallation = Version >= ClientVersion.CV_7000 && File.Exists(UOFileManager.GetUOFilePath("MainMisc.uop"));
            Protocol          = ClientFlags.CF_T2A;

            if (Version >= ClientVersion.CV_200)
            {
                Protocol |= ClientFlags.CF_RE;
            }
            if (Version >= ClientVersion.CV_300)
            {
                Protocol |= ClientFlags.CF_TD;
            }
            if (Version >= ClientVersion.CV_308)
            {
                Protocol |= ClientFlags.CF_LBR;
            }
            if (Version >= ClientVersion.CV_308Z)
            {
                Protocol |= ClientFlags.CF_AOS;
            }
            if (Version >= ClientVersion.CV_405A)
            {
                Protocol |= ClientFlags.CF_SE;
            }
            if (Version >= ClientVersion.CV_60144)
            {
                Protocol |= ClientFlags.CF_SA;
            }

            Log.Trace($"Client path: '{clientPath}'");
            Log.Trace($"Client version: {clientVersion}");
            Log.Trace($"Protocol: {Protocol}");
            Log.Trace("UOP? " + (IsUOPInstallation ? "yes" : "no"));

            // ok now load uo files
            UOFileManager.Load();
            StaticFilters.Load();

            Log.Trace("Network calibration...");
            PacketHandlers.Load();
            //ATTENTION: you will need to enable ALSO ultimalive server-side, or this code will have absolutely no effect!
            //UltimaLive.Enable();
            PacketsTable.AdjustPacketSizeByVersion(Version);

            if (Settings.GlobalSettings.Encryption != 0)
            {
                Log.Trace("Calculating encryption by client version...");
                EncryptionHelper.CalculateEncryption(Version);
                Log.Trace($"encryption: {EncryptionHelper.Type}");

                if (EncryptionHelper.Type != (ENCRYPTION_TYPE)Settings.GlobalSettings.Encryption)
                {
                    Log.Warn($"Encryption found: {EncryptionHelper.Type}");
                    Settings.GlobalSettings.Encryption = (byte)EncryptionHelper.Type;
                }
            }

            Log.Trace("Done!");

            Log.Trace("Loading plugins...");

            foreach (var p in Settings.GlobalSettings.Plugins)
            {
                Plugin.Create(p);
            }
            Log.Trace("Done!");

            //UoAssist.Start();

            Log.Trace(">>>>>>>>>>>>> DONE >>>>>>>>>>>>>");
        }
Exemplo n.º 8
0
    public void StartGame(ServerConfiguration config)
    {
        CUOEnviroment.ExecutablePath = config.GetPathToSaveFiles();

        //Load and adjust settings
        var settingsFilePath = Settings.GetSettingsFilepath();

        if (File.Exists(settingsFilePath))
        {
            Settings.GlobalSettings = JsonConvert.DeserializeObject <Settings>(File.ReadAllText(settingsFilePath));
        }
        else
        {
            Settings.GlobalSettings = JsonConvert.DeserializeObject <Settings>(Resources.Load <TextAsset>("settings").text);
        }

        Settings.GlobalSettings.IP   = config.UoServerUrl;
        Settings.GlobalSettings.Port = ushort.Parse(config.UoServerPort);

        //Reset static encryption type variable
        EncryptionHelper.Type = ENCRYPTION_TYPE.NONE;
        Settings.GlobalSettings.Encryption = (byte)(config.UseEncryption ? 1 : 0);

        //Empty the plugins array because no plugins are working at the moment
        Settings.GlobalSettings.Plugins = new string[0];

        //If connecting to UO Outlands, set shard type to 2 for outlands
        Settings.GlobalSettings.ShardType = config.UoServerUrl.ToLower().Contains("uooutlands") ? 2 : 0;

        //Try to detect old client version to set ShardType to 1, for using StatusGumpOld. Otherwise, it's possible
        //to get null-refs in StatusGumpModern.
        if (ClientVersionHelper.IsClientVersionValid(config.ClientVersion, out var clientVersion))
        {
            if (clientVersion < ClientVersion.CV_308Z)
            {
                Settings.GlobalSettings.ShardType = 1;
            }
        }

        CUOEnviroment.IsOutlands = Settings.GlobalSettings.ShardType == 2;

        Settings.GlobalSettings.ClientVersion = config.ClientVersion;

        if (Application.isMobilePlatform == false && string.IsNullOrEmpty(config.ClientPathForUnityEditor) == false)
        {
            Settings.GlobalSettings.UltimaOnlineDirectory = config.ClientPathForUnityEditor;
        }
        else
        {
            Settings.GlobalSettings.UltimaOnlineDirectory = config.GetPathToSaveFiles();
        }

        //This flag is tied to whether the GameCursor gets drawn, in a convoluted way
        //On mobile platform, set this flag to true to prevent the GameCursor from being drawn
        Settings.GlobalSettings.RunMouseInASeparateThread = Application.isMobilePlatform;

        //Some mobile specific overrides need to be done on the Profile but they can only be done once the Profile has been loaded
        ProfileManager.ProfileLoaded += OnProfileLoaded;

        // Add an audio source and tell the media player to use it for playing sounds
        Log.Start(LogTypes.All);

        try
        {
            Client.SceneChanged += OnSceneChanged;
            Client.Run();
#if ENABLE_INTERNAL_ASSISTANT
            if (UserPreferences.EnableAssistant.CurrentValue == (int)PreferenceEnums.EnableAssistant.On)
            {
                Plugin.LoadInternalAssistant();
            }
#endif
            Client.Game.Exiting += OnGameExiting;
            ApplyScalingFactor();

            if (UserPreferences.ShowModifierKeyButtons.CurrentValue == (int)PreferenceEnums.ShowModifierKeyButtons.On)
            {
                modifierKeyButtonsParent.SetActive(true);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            OnError?.Invoke(e.ToString());
        }
    }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

            Log.Start(LogTypes.All);

            CUOEnviroment.GameThread      = Thread.CurrentThread;
            CUOEnviroment.GameThread.Name = "CUO_MAIN_THREAD";

#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.AppendLine("######################## [START LOG] ########################");

#if DEV_BUILD
                sb.AppendLine($"ClassicUO [DEV_BUILD] - {CUOEnviroment.Version} - {DateTime.Now}");
#else
                sb.AppendLine($"ClassicUO [STANDARD_BUILD] - {CUOEnviroment.Version} - {DateTime.Now}");
#endif

                sb.AppendLine
                    ($"OS: {Environment.OSVersion.Platform} {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}");

                sb.AppendLine($"Thread: {Thread.CurrentThread.Name}");
                sb.AppendLine();

                if (Settings.GlobalSettings != null)
                {
                    sb.AppendLine($"Shard: {Settings.GlobalSettings.IP}");
                    sb.AppendLine($"ClientVersion: {Settings.GlobalSettings.ClientVersion}");
                    sb.AppendLine();
                }

                sb.AppendFormat("Exception:\n{0}\n", e.ExceptionObject);
                sb.AppendLine("######################## [END LOG] ########################");
                sb.AppendLine();
                sb.AppendLine();

                Log.Panic(e.ExceptionObject.ToString());
                string path = Path.Combine(CUOEnviroment.ExecutablePath, "Logs");

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                using (LogFile crashfile = new LogFile(path, "crash.txt"))
                {
                    crashfile.WriteAsync(sb.ToString()).RunSynchronously();
                }
            };
#endif
            ReadSettingsFromArgs(args);

#if DEV_BUILD
            if (!_skipUpdates)
            {
                Network.Updater updater = new Network.Updater();
                if (updater.Check())
                {
                    return;
                }
            }
#endif

            if (!_skipUpdates)
            {
                if (CheckUpdate(args))
                {
                    return;
                }
            }

            if (CUOEnviroment.IsHighDPI)
            {
                Environment.SetEnvironmentVariable("FNA_GRAPHICS_ENABLE_HIGHDPI", "1");
            }

            Environment.SetEnvironmentVariable("FNA3D_BACKBUFFER_SCALE_NEAREST", "1");
            Environment.SetEnvironmentVariable("FNA3D_OPENGL_FORCE_COMPATIBILITY_PROFILE", "1");
            Environment.SetEnvironmentVariable(SDL.SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");

            Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Plugins"));

            string globalSettingsPath = Settings.GetSettingsFilepath();

            if (!Directory.Exists(Path.GetDirectoryName(globalSettingsPath)) || !File.Exists(globalSettingsPath))
            {
                // settings specified in path does not exists, make new one
                {
                    // TODO:
                    Settings.GlobalSettings.Save();
                }
            }

            Settings.GlobalSettings  = ConfigurationResolver.Load <Settings>(globalSettingsPath);
            CUOEnviroment.IsOutlands = Settings.GlobalSettings.ShardType == 2;

            ReadSettingsFromArgs(args);

            // still invalid, cannot load settings
            if (Settings.GlobalSettings == null)
            {
                Settings.GlobalSettings = new Settings();
                Settings.GlobalSettings.Save();
            }

            if (!CUOEnviroment.IsUnix)
            {
                string libsPath = Path.Combine(CUOEnviroment.ExecutablePath, Environment.Is64BitProcess ? "x64" : "x86");

                SetDllDirectory(libsPath);
            }


            if (string.IsNullOrWhiteSpace(Settings.GlobalSettings.UltimaOnlineDirectory))
            {
                Settings.GlobalSettings.UltimaOnlineDirectory = CUOEnviroment.ExecutablePath;
            }

            const uint INVALID_UO_DIRECTORY = 0x100;
            const uint INVALID_UO_VERSION   = 0x200;

            uint flags = 0;

            if (!Directory.Exists(Settings.GlobalSettings.UltimaOnlineDirectory) || !File.Exists(UOFileManager.GetUOFilePath("tiledata.mul")))
            {
                flags |= INVALID_UO_DIRECTORY;
            }

            string clientVersionText = Settings.GlobalSettings.ClientVersion;

            if (!ClientVersionHelper.IsClientVersionValid(Settings.GlobalSettings.ClientVersion, out ClientVersion clientVersion))
            {
                Log.Warn($"Client version [{clientVersionText}] is invalid, let's try to read the client.exe");

                // mmm something bad happened, try to load from client.exe [windows only]
                if (!ClientVersionHelper.TryParseFromFile(Path.Combine(Settings.GlobalSettings.UltimaOnlineDirectory, "client.exe"), out clientVersionText) || !ClientVersionHelper.IsClientVersionValid(clientVersionText, out clientVersion))
                {
                    Log.Error("Invalid client version: " + clientVersionText);

                    flags |= INVALID_UO_VERSION;
                }
                else
                {
                    Log.Trace($"Found a valid client.exe [{clientVersionText} - {clientVersion}]");

                    // update the wrong/missing client version in settings.json
                    Settings.GlobalSettings.ClientVersion = clientVersionText;
                }
            }

            if (flags != 0)
            {
                if ((flags & INVALID_UO_DIRECTORY) != 0)
                {
                    Client.ShowErrorMessage(ResGeneral.YourUODirectoryIsInvalid);
                }
                else if ((flags & INVALID_UO_VERSION) != 0)
                {
                    Client.ShowErrorMessage(ResGeneral.YourUOClientVersionIsInvalid);
                }

                PlatformHelper.LaunchBrowser(ResGeneral.ClassicUOLink);
            }
            else
            {
                switch (Settings.GlobalSettings.ForceDriver)
                {
                case 1:     // OpenGL
                    Environment.SetEnvironmentVariable("FNA3D_FORCE_DRIVER", "OpenGL");

                    break;

                case 2:     // Vulkan
                    Environment.SetEnvironmentVariable("FNA3D_FORCE_DRIVER", "Vulkan");

                    break;
                }

                Client.Run();
            }

            Log.Trace("Closing...");
        }
Exemplo n.º 10
0
        private async Task <string> AuthenticateAsync(string server, NetworkCredential credential)
        {
            using (var client = GetHttpClient(false))
            {
                var host = $"https://{server}:{ClientConstants.AuthorizationServerPort}/connect/token";

                Log.Information($"Authenticating at {host}");


                var parameters = new Dictionary <string, string>()
                {
                    { ClientConstants.DeviceIdClaim, _idService.GetDeviceId() },
                    { ClientConstants.VersionClaim, ClientVersionHelper.GetVersion() }
                };

                if (_domain != null)
                {
                    parameters.Add(ClientConstants.DomainClaim, _domain);
                }

                TokenResponse tokenResponse = null;
                if (credential != null)
                {
                    UserName      = credential.UserName;
                    tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
                    {
                        Address      = host,
                        ClientId     = _environment.GetClientId(),
                        ClientSecret = "xtreamer.id",

                        UserName = _appResources.AppData.UserNamePrefix + credential.UserName,
                        Password = credential.Password,
                        Scope    = ClientConstants.ConnectionServerApi,

                        Parameters = parameters
                    });
                }
                else
                {
                    UserName      = null;
                    tokenResponse = await client.RequestTokenAsync(new TokenRequest
                    {
                        Address      = host,
                        ClientId     = _environment.GetClientId(),
                        ClientSecret = "xtreamer.id",
                        GrantType    = ClientConstants.AnonymousGrandType,

                        Parameters = parameters
                    });
                }

                if (tokenResponse.IsError)
                {
                    if (tokenResponse.ErrorType == ResponseErrorType.Exception &&
                        tokenResponse.Exception is HttpRequestException &&
                        tokenResponse.Exception.InnerException is SocketException)
                    {
                        throw new ConnectionServiceException("Connection to the service failed. Please check your internet connection.", tokenResponse.Exception);
                    }
                    else if (credential != null &&
                             tokenResponse.ErrorType == ResponseErrorType.Protocol &&
                             tokenResponse.HttpResponse?.StatusCode == HttpStatusCode.BadRequest &&
                             tokenResponse.ErrorDescription == "invalid_username_or_password")
                    {
                        throw new WrongUserNamePasswordException();
                    }
                    else
                    {
                        throw new ConnectionServiceException($"Unknown error occured ({tokenResponse.Error}). Please contact service administrator.", tokenResponse.Exception);
                    }
                }

                var jwt     = tokenResponse.AccessToken;
                var handler = new JwtSecurityTokenHandler();
                var token   = handler.ReadJwtToken(jwt);

                Claims = new ClientClaims(token.Claims);

                if (Claims.IsDebug)
                {
                    _logService.EnableDebug();
                }

                return(tokenResponse.AccessToken);
            }
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            // - check for update
            // - launcher & user setup
            // - game setup
            // - game launch
            // - enjoy

            CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

            Log.Start(LogTypes.All);

            CUOEnviroment.GameThread      = Thread.CurrentThread;
            CUOEnviroment.GameThread.Name = "CUO_MAIN_THREAD";


#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("######################## [START LOG] ########################");

#if DEV_BUILD
                sb.AppendLine($"ClassicUO [DEV_BUILD] - {CUOEnviroment.Version}");
#else
                sb.AppendLine($"ClassicUO [STANDARD_BUILD] - {CUOEnviroment.Version}");
#endif

                sb.AppendLine($"OS: {Environment.OSVersion.Platform} x{(Environment.Is64BitOperatingSystem ? "64" : "86")}");
                sb.AppendLine($"Thread: {Thread.CurrentThread.Name}");
                sb.AppendLine();

                sb.AppendLine($"Protocol: {Client.Protocol}");
                sb.AppendLine($"ClientFeatures: {World.ClientFeatures.Flags}");
                sb.AppendLine($"ClientLockedFeatures: {World.ClientLockedFeatures.Flags}");
                sb.AppendLine($"ClientVersion: {Client.Version}");

                sb.AppendLine();
                sb.AppendFormat("Exception:\n{0}\n", e.ExceptionObject);
                sb.AppendLine("######################## [END LOG] ########################");
                sb.AppendLine();
                sb.AppendLine();

                Log.Panic(e.ExceptionObject.ToString());
                string path = Path.Combine(CUOEnviroment.ExecutablePath, "Logs");

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                using (LogFile crashfile = new LogFile(path, "crash.txt"))
                {
                    crashfile.WriteAsync(sb.ToString()).RunSynchronously();
                }
            };
#endif
            ReadSettingsFromArgs(args);

#if DEV_BUILD
            if (!_skipUpdates)
            {
                Updater updater = new Updater();
                if (updater.Check())
                {
                    return;
                }
            }
#endif

            if (!_skipUpdates)
            {
                if (CheckUpdate(args))
                {
                    return;
                }
            }

            //Environment.SetEnvironmentVariable("FNA_GRAPHICS_FORCE_GLDEVICE", "ModernGLDevice");
            if (CUOEnviroment.IsHighDPI)
            {
                Log.Trace("HIGH DPI - ENABLED");
                Environment.SetEnvironmentVariable("FNA_GRAPHICS_ENABLE_HIGHDPI", "1");
            }
            Environment.SetEnvironmentVariable("FNA_OPENGL_BACKBUFFER_SCALE_NEAREST", "1");
            Environment.SetEnvironmentVariable("FNA_OPENGL_FORCE_COMPATIBILITY_PROFILE", "1");
            Environment.SetEnvironmentVariable(SDL.SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
            Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Plugins"));


            string globalSettingsPath = Settings.GetSettingsFilepath();

            if ((!Directory.Exists(Path.GetDirectoryName(globalSettingsPath)) ||
                 !File.Exists(globalSettingsPath)))
            {
                // settings specified in path does not exists, make new one
                {
                    // TODO:
                    Settings.GlobalSettings.Save();

                    if (!Directory.Exists(Settings.GlobalSettings.UltimaOnlineDirectory) ||
                        !ClientVersionHelper.IsClientVersionValid(Settings.GlobalSettings.ClientVersion, out _))
                    {
                        return;
                    }
                }
            }

            Settings.GlobalSettings = ConfigurationResolver.Load <Settings>(globalSettingsPath);

            ReadSettingsFromArgs(args);

            // still invalid, cannot load settings
            if (Settings.GlobalSettings == null)
            {
                Settings.GlobalSettings = new Settings();
                Settings.GlobalSettings.Save();
            }

            if (!CUOEnviroment.IsUnix)
            {
                string libsPath = Path.Combine(CUOEnviroment.ExecutablePath, "libs", Environment.Is64BitProcess ? "x64" : "x86");
                SetDllDirectory(libsPath);
            }

            if (string.IsNullOrWhiteSpace(Settings.GlobalSettings.UltimaOnlineDirectory))
            {
                Settings.GlobalSettings.UltimaOnlineDirectory = CUOEnviroment.ExecutablePath;
            }


            Client.Run();

            Log.Trace("Closing...");
        }
Exemplo n.º 12
0
        private async Task LoginAsync(bool asRegistered)
        {
            ControlsEnabled.Value = false;
            bool succeed = false;

            try
            {
                _environment.SetHighPriorityToApplication();
                _environment.StartObtainProcessorName();

                await StoreLoginData(asRegistered);

                if (asRegistered && (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)))
                {
                    throw new WrongUserNamePasswordException();
                }

                NetworkCredential credentials = asRegistered ? new NetworkCredential(UserName, Password) : null;

                _notificationService.SetProgress("Initializing...");

                _main.BeforeConnect();
                await _idService.WaitDeviceId();

                var response = await _connectionService.StartAsync(credentials);

                bool updateUrgent = ClientVersionHelper.IsBreakingChange(response.UpperVersions);
                if (!updateUrgent)
                {
                    await _main.StartAsync();

                    var readyToDisplay = Task.Delay(800);
                    Connected.Value = true;

                    await _main.DisplayAsync(readyToDisplay, response.UpperVersions, _connectionService.Claims.AppUpdatePath);

                    _notificationService.Clear(this);
                }
                else
                {
                    _notificationService.Clear(this);
                    _updateModel.Display(response);
                }
                succeed = true;
            }
            catch (WrongUserNamePasswordException)
            {
                _notificationService.SetError(this, "Wrong user name/password or your account is not active");
            }
            catch (ConnectionServiceException e)
            {
                _notificationService.SetError(this, e.Message, e);
            }
            catch (HubConnectionException e)
            {
                _notificationService.SetError(this, $"Something went wrong with app. Please contact service administrator ({e.Message})", e);
            }
            catch (Exception e)
            {
                _notificationService.SetError(this, $"Something went wrong with the app. Please contact service administrator ({e.Message})", e);
            }

            if (!succeed)
            {
                Connected.Value       = false;
                ControlsEnabled.Value = true;
                ControlsVisible.Value = true;
            }
        }