Skip to content

[Bug]: LicenseListCallback didn't work #1412

@scx1125

Description

@scx1125

What did you expect to happen?

LicenseListCallback does not have any callbacks after login is complete

Instead of that, what actually happened?

LicenseListCallback does not have any callbacks after login is complete

Which operating system are you running on?

Windows

Which .NET Runtime are you running on?

.NET Core or .NET 5 or higher.

Version

.NET 8

Relevant log output

private async Task CheckAccountTask(SteamAccount stAccount, CancellationToken cancellationToken)
        {
            if (_cancellationTokenSource == null)
            {
                stAccount.Log = "任务已取消";
                return; // 如果已经停止,不执行任务
            }
            string previouslyStoredGuardData = null;
            var credentials = new Credentials();
            var steamClient = new SteamClient();
            
            var steamUser = steamClient.GetHandler<SteamUser>();
            var steamApps = steamClient.GetHandler<SteamApps>();
            var steamUnifiedMessages = steamClient.GetHandler<SteamUnifiedMessages>();
            var manager = new CallbackManager(steamClient);
            manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
            manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);

            manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
            manager.Subscribe<SteamApps.LicenseListCallback>(LicenseListCallback);
            manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
            

            var isRunning = true;

            Console.WriteLine("Connecting to Steam...");
            stAccount.Log = "正在连接到Steam...";
            steamClient.Connect();

            while (isRunning)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine("Task canceled");
                    stAccount.Log = "任务已取消";
                    break;
                }
                manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }

            async void OnConnected(SteamClient.ConnectedCallback callback)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine("Task canceled during connection");
                    stAccount.Log = "任务在连接时取消";
                    return;
                }
                //steamUser.LogOnAnonymous();


                var shouldRememberPassword = true;

                // Begin authenticating via credentials
                var authSession = await steamClient.Authentication.BeginAuthSessionViaCredentialsAsync(new AuthSessionDetails
                {
                    Username = stAccount.Username,
                    Password = stAccount.Password,
                    IsPersistentSession = shouldRememberPassword,
                    GuardData = previouslyStoredGuardData,
                    Authenticator = new UserConsoleAuthenticator(),
                });
                var pollResponse = await authSession.PollingWaitForResultAsync();

                if (pollResponse.NewGuardData != null)
                {
                    previouslyStoredGuardData = pollResponse.NewGuardData;
                }

                steamUser.LogOn(new SteamUser.LogOnDetails
                {
                    Username = pollResponse.AccountName,
                    AccessToken = pollResponse.RefreshToken,
                    ShouldRememberPassword = shouldRememberPassword,
                });

                ParseJsonWebToken(pollResponse.AccessToken, nameof(pollResponse.AccessToken));
                ParseJsonWebToken(pollResponse.RefreshToken, nameof(pollResponse.RefreshToken));
            }

            void OnDisconnected(SteamClient.DisconnectedCallback callback)
            {
                Console.WriteLine("Disconnected from Steam");
                stAccount.Log = "与Steam断开连接";
                const int maxRetryAttempts = 3;
                int retryCount = 0;
                bool reconnected = false;

                while (retryCount < maxRetryAttempts && !reconnected)
                {
                    retryCount++;
                    Console.WriteLine($"Disconnected from Steam. Attempting to reconnect... ({retryCount}/{maxRetryAttempts})");
                    stAccount.Log = $"与Steam断开连接,正在尝试重新连接... ({retryCount}/{maxRetryAttempts})";

                    // 尝试重新连接
                    steamClient.Connect();

                    // 等待一段时间再检查连接状态
                    Task.Delay(TimeSpan.FromSeconds(5)).Wait();

                    if (steamClient.IsConnected)
                    {
                        Console.WriteLine("Reconnected to Steam successfully.");
                        stAccount.Log = "成功重新连接到Steam";
                        reconnected = true;
                    }
                }

                if (!reconnected)
                {
                    Console.WriteLine("Failed to reconnect after 3 attempts.");
                    stAccount.Log = "尝试3次后仍无法重新连接";
                    isRunning = false; // 停止任务
                }
            }

            void OnLoggedOn(SteamUser.LoggedOnCallback callback)
            {
                if (callback.Result != EResult.OK)
                {
                    Console.WriteLine("Unable to logon to Steam: {0} / {1}", callback.Result, callback.ExtendedResult);
                    stAccount.Log = $"无法登录到Steam: {callback.Result} / {callback.ExtendedResult}";

                    isRunning = false;
                    return;
                }

                Console.WriteLine("Successfully logged on!");
                stAccount.Log = "登录成功";
                //功能
                isRunning = false;
                //steamUser.LogOff();
            }


            void LicenseListCallback(SteamApps.LicenseListCallback licenseList)
            {
                if (licenseList.Result != EResult.OK)
                {
                    Console.WriteLine("Unable to get license list: {0} ", licenseList.Result);
                    return;
                }

                Trace.WriteLine($"Got {licenseList.LicenseList.Count} licenses for account!" );
                var Licenses = licenseList.LicenseList;

                IEnumerable<uint> licenseQuery = Licenses.Select(lic =>
                {
                    Trace.WriteLine(lic.PackageID);
                    return lic.PackageID;
                });

                Console.WriteLine("Licenses: {0}", string.Join(", ", licenseQuery));
            }

            void OnLoggedOff(SteamUser.LoggedOffCallback callback)
            {
                Console.WriteLine("Logged off of Steam: {0}", callback.Result);
                stAccount.Log = $"已从Steam注销: {callback.Result}";
            }

            void ParseJsonWebToken(string token, string name)
            {
                var tokenComponents = token.Split('.');

                var base64 = tokenComponents[1].Replace('-', '+').Replace('_', '/');

                if (base64.Length % 4 != 0)
                {
                    base64 += new string('=', 4 - base64.Length % 4);
                }

                var payloadBytes = Convert.FromBase64String(base64);

                var payload = JsonDocument.Parse(payloadBytes);

                var formatted = JsonSerializer.Serialize(payload, new JsonSerializerOptions
                {
                    WriteIndented = true,
                });
                Console.WriteLine($"{name}: {formatted}");
                Console.WriteLine();
            }
        }

Example Code

No response

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions