Пример #1
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            log.Debug(msg.ToString());
            msg.Handle <SteamGameCoordinator.MessageCallback>(callback =>
            {
                Console.WriteLine(callback.EMsg);
            });

            msg.Handle <ClientPlayerNicknameListHandler.ClientPlayerNicknameListCallback>(callback =>
            {
                foreach (var player in callback.Nicknames)
                {
                    PlayerNicknames.Add(player.steamid, player.nickname);
                }
            });

            #region Login
            msg.Handle <SteamClient.ConnectedCallback> (callback =>
            {
                log.Debug("Connection Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    UserLogOn();
                }
                else
                {
                    log.Error("Failed to connect to Steam Community, trying again...");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Failed to connect to Steam Community, trying again...";
                    }));
                    SteamClient.Connect();
                }
            });

            msg.Handle <SteamUser.LoggedOnCallback> (callback =>
            {
                log.Debug("Logged On Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    MyLoginKey = callback.WebAPIUserNonce;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in to Steam...";
                        log.Info("Logging in to Steam...");
                    }));
                }

                if (callback.Result != EResult.OK)
                {
                    log.Error("Login Error: " + callback.Result);
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Login Error: " + callback.Result;
                    }));
                }

                if (callback.Result == EResult.InvalidPassword)
                {
                    MetroFramework.MetroMessageBox.Show(main, "Your password is incorrect. Please try again.",
                                                        "Invalid Password",
                                                        MessageBoxButtons.OK,
                                                        MessageBoxIcon.Error,
                                                        MessageBoxDefaultButton.Button1);
                    main.wrongAPI = true;
                    main.Invoke((Action)(main.Close));
                    return;
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    SteamGuard SteamGuard = new SteamGuard();
                    SteamGuard.ShowDialog();
                    logOnDetails.AuthCode = SteamGuard.AuthCode;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in...";
                    }));
                    SteamClient.Connect();
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("An Invalid Authorization Code was provided.  Enter the authentication code sent to the proper email: ");
                    SteamGuard SteamGuard = new SteamGuard("An Invalid Authorization Code was provided.\nEnter the authentication code sent to the proper email: ");
                    SteamGuard.ShowDialog();
                    logOnDetails.AuthCode = SteamGuard.AuthCode;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in...";
                    }));
                    SteamClient.Connect();
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback> (callback =>
            {
                log.Debug("Handling LoginKeyCallback...");
                while (true)
                {
                    try
                    {
                        log.Info("About to authenticate...");
                        main.Invoke((Action)(() =>
                        {
                            main.label_status.Text = "Authenticating...";
                        }));
                        bool authd = false;
                        try
                        {
                            authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Error on authentication:\n" + ex);
                        }
                        if (authd)
                        {
                            log.Success("User authenticated!");
                            main.Invoke((Action)(() =>
                            {
                                main.label_status.Text = "User authenticated!";
                            }));
                            tradeManager = new TradeManager(apiKey, sessionId, token);
                            tradeManager.SetTradeTimeLimits(0, 0, TradePollingInterval);
                            tradeManager.OnTimeout += OnTradeTimeout;
                            break;
                        }
                        else
                        {
                            log.Warn("Authentication failed, retrying in 2s...");
                            main.Invoke((Action)(() =>
                            {
                                main.label_status.Text = "Authentication failed, retrying in 2s...";
                            }));
                            Thread.Sleep(2000);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.ToString());
                    }
                }

                SteamFriends.SetPersonaName(SteamFriends.GetFriendPersonaName(SteamUser.SteamID));
                SteamFriends.SetPersonaState(EPersonaState.Online);
                log.Success("Account Logged In Completely!");
                main.Invoke((Action)(() =>
                {
                    main.label_status.Text = "Logged in completely!";
                }));
                botCookies = new CookieContainer();
                botCookies.SetCookies(new Uri("http://steamcommunity.com"), string.Format("steamLogin={0}", token));
                botCookies.SetCookies(new Uri("http://steamcommunity.com"), string.Format("sessionid={0}", sessionId));
                GenericInventory.SetCookie(botCookies, SteamUser.SteamID);

                IsLoggedIn = true;
                try
                {
                    main.Invoke((Action)(main.Hide));
                }
                catch (Exception)
                {
                    Environment.Exit(1);
                }

                new Thread(() =>
                {
                    CDNCache.Initialize();
                    #if !DEBUG
                    ConnectToGC(13540830642081628378);
                    System.Threading.Thread.Sleep(2000);
                    ConnectToGC(0);
                    #endif
                    while (true)
                    {
                        if (showFriends != null)
                        {
                            var numFriendsDisplayed = showFriends.GetNumFriendsDisplayed();
                            var numSteamFriendCount = SteamFriends.GetFriendCount();
                            if (numFriendsDisplayed != -1 && numFriendsDisplayed != ListFriends.Get().Count)
                            {
                                LoadFriends();
                                showFriends.UpdateFriendsHTML();
                            }
                            System.Threading.Thread.Sleep(10000);
                        }
                    }
                }).Start();
            });

            // handle a special JobCallback differently than the others
            if (msg.IsType <SteamClient.JobCallback <SteamUser.UpdateMachineAuthCallback> >())
            {
                msg.Handle <SteamClient.JobCallback <SteamUser.UpdateMachineAuthCallback> >(
                    jobCallback => OnUpdateMachineAuthCallback(jobCallback.Callback, jobCallback.JobID)
                    );
            }
            #endregion

            msg.Handle <SteamUser.AccountInfoCallback>(callback =>
            {
                DisplayName = callback.PersonaName;
            });

            #region Friends
            msg.Handle <SteamFriends.FriendsListCallback>(callback =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (friend.SteamID.AccountType == EAccountType.Clan)
                    {
                    }
                    else
                    {
                        if (!friends.Contains(friend.SteamID))
                        {
                            new Thread(() =>
                            {
                                main.Invoke((Action)(() =>
                                {
                                    if (showFriends == null && friend.Relationship == EFriendRelationship.RequestRecipient)
                                    {
                                        log.Info(SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                        friends.Add(friend.SteamID);
                                        string name = SteamFriends.GetFriendPersonaName(friend.SteamID);
                                        string status = SteamFriends.GetFriendPersonaState(friend.SteamID).ToString();
                                        if (!ListFriendRequests.Find(friend.SteamID))
                                        {
                                            ListFriendRequests.Add(name, friend.SteamID, status);
                                        }
                                    }
                                    if (showFriends != null && friend.Relationship == EFriendRelationship.RequestRecipient)
                                    {
                                        log.Info(SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                        friends.Add(friend.SteamID);
                                        string name = SteamFriends.GetFriendPersonaName(friend.SteamID);
                                        string status = SteamFriends.GetFriendPersonaState(friend.SteamID).ToString();
                                        if (!ListFriendRequests.Find(friend.SteamID))
                                        {
                                            try
                                            {
                                                ListFriendRequests.Add(name, friend.SteamID, status);
                                                log.Info("Notifying you that " + SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                                int duration = 5;
                                                FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
                                                FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
                                                Notification toastNotification = new Notification(name, Util.GetColorFromPersonaState(this, friend.SteamID), "has sent you a friend request.", duration, animationMethod, animationDirection);
                                                toastNotification.Show();
                                                try
                                                {
                                                    string soundsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
                                                    string soundFile = Path.Combine(soundsFolder + "trade_message.wav");
                                                    using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(soundFile))
                                                    {
                                                        player.Play();
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    Console.WriteLine(e.Message);
                                                }
                                            }
                                            catch
                                            {
                                                Console.WriteLine("Friends list hasn't loaded yet...");
                                            }
                                        }
                                    }
                                }));
                            }).Start();
                        }
                        else
                        {
                            if (friend.Relationship == EFriendRelationship.None)
                            {
                                friends.Remove(friend.SteamID);
                                GetUserHandler(friend.SteamID).OnFriendRemove();
                                RemoveUserHandler(friend.SteamID);
                            }
                        }
                    }
                }
                LoadFriends();
            });

            msg.Handle <SteamFriends.PersonaStateCallback>(callback =>
            {
                var status = callback.State;
                var sid    = callback.FriendID;
                ListFriends.UpdateStatus(sid, status.ToString());
                ListFriends.UpdateName(sid, SteamFriends.GetFriendPersonaName(sid));
                GetUserHandler(sid).UpdatePersonaState();
                if (showFriends != null)
                {
                    showFriends.UpdateState();
                    showFriends.UpdateFriendHTML(sid);
                }
            });


            msg.Handle <SteamFriends.FriendMsgCallback>(callback =>
            {
                EChatEntryType type = callback.EntryType;

                if (type == EChatEntryType.Typing)
                {
                    var name = SteamFriends.GetFriendPersonaName(callback.Sender);
                    GetUserHandler(callback.Sender).SetChatStatus(name + " is typing...");
                    System.Threading.Thread.Sleep(30000);
                    GetUserHandler(callback.Sender).SetChatStatus("");
                }

                if (type == EChatEntryType.ChatMsg)
                {
                    GetUserHandler(callback.Sender).SetChatStatus("");
                    GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
                }
            });

            msg.Handle <SteamFriends.ChatMsgCallback>(callback =>
            {
                Console.WriteLine(SteamFriends.GetFriendPersonaName(callback.ChatterID) + ": " + callback.Message);
            });
            #endregion

            #region Trading
            msg.Handle <SteamTrading.SessionStartCallback>(callback =>
            {
                bool started = HandleTradeSessionStart(callback.OtherClient);

                if (!started)
                {
                    log.Error("Could not start the trade session.");
                }
                else
                {
                    log.Debug("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
                }
            });

            msg.Handle <SteamTrading.TradeProposedCallback>(callback =>
            {
                try
                {
                    tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
                }
                catch
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

                //if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ())
                if (CurrentTrade == null)
                {
                    GetUserHandler(callback.OtherClient).SendTradeState(callback.TradeID);
                }
                else
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                }
            });

            msg.Handle <SteamTrading.TradeResultCallback>(callback =>
            {
                //log.Debug ("Trade Status: " + callback.Response);

                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    //log.Info ("Trade Accepted!");
                }
                else if (callback.Response == EEconTradeResponse.Cancel ||
                         callback.Response == EEconTradeResponse.ConnectionFailed ||
                         callback.Response == EEconTradeResponse.Declined ||
                         callback.Response == EEconTradeResponse.AlreadyHasTradeRequest ||
                         callback.Response == EEconTradeResponse.AlreadyTrading ||
                         callback.Response == EEconTradeResponse.TargetAlreadyTrading ||
                         callback.Response == EEconTradeResponse.NoResponse ||
                         callback.Response == EEconTradeResponse.TooSoon ||
                         callback.Response == EEconTradeResponse.TradeBannedInitiator ||
                         callback.Response == EEconTradeResponse.TradeBannedTarget ||
                         callback.Response == EEconTradeResponse.NotLoggedIn)
                {
                    if (callback.Response == EEconTradeResponse.Cancel)
                    {
                        TradeResponse(callback.OtherClient, "had asked to trade with you, but has cancelled their request.");
                    }
                    if (callback.Response == EEconTradeResponse.ConnectionFailed)
                    {
                        TradeResponse(callback.OtherClient, "Lost connection to Steam. Reconnecting as soon as possible...");
                    }
                    if (callback.Response == EEconTradeResponse.Declined)
                    {
                        TradeResponse(callback.OtherClient, "has declined your trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.AlreadyHasTradeRequest)
                    {
                        TradeResponse(callback.OtherClient, "An error has occurred in sending the trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.AlreadyTrading)
                    {
                        TradeResponse(callback.OtherClient, "You are already in a trade so you cannot trade someone else.");
                    }
                    if (callback.Response == EEconTradeResponse.TargetAlreadyTrading)
                    {
                        TradeResponse(callback.OtherClient, "You cannot trade the other user because they are already in trade with someone else.");
                    }
                    if (callback.Response == EEconTradeResponse.NoResponse)
                    {
                        TradeResponse(callback.OtherClient, "did not respond to the trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.TooSoon)
                    {
                        TradeResponse(callback.OtherClient, "It is too soon to send a new trade request. Try again later.");
                    }
                    if (callback.Response == EEconTradeResponse.TradeBannedInitiator)
                    {
                        TradeResponse(callback.OtherClient, "You are trade-banned and cannot trade.");
                    }
                    if (callback.Response == EEconTradeResponse.TradeBannedTarget)
                    {
                        TradeResponse(callback.OtherClient, "You cannot trade with this person because they are trade-banned.");
                    }
                    if (callback.Response == EEconTradeResponse.NotLoggedIn)
                    {
                        TradeResponse(callback.OtherClient, "Trade failed to initialize because you are not logged in.");
                    }
                    CloseTrade();
                }
            });
            #endregion

            #region Disconnect
            msg.Handle <SteamUser.LoggedOffCallback> (callback =>
            {
                IsLoggedIn = false;
                log.Warn("Logged Off: " + callback.Result);
            });

            msg.Handle <SteamClient.DisconnectedCallback> (callback =>
            {
                if (IsLoggedIn)
                {
                    IsLoggedIn = false;
                    CloseTrade();
                    log.Warn("Disconnected from Steam Network!");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Disconnected from Steam Network! Retrying...";
                    }));
                    SteamClient.Connect();
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Connecting to Steam...";
                    }));
                }
            });
            #endregion

            if (!hasrun && IsLoggedIn)
            {
                Thread main = new Thread(GUI);
                main.Start();
                hasrun = true;
            }
        }