Exemplo n.º 1
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            log.Debug(msg.ToString());

            #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)
                {
                    MessageBox.Show("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...";
                    }));
                }

                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...";
                    }));
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback> (callback =>
            {
                log.Debug("Handling LoginKeyCallback...");

                while (true)
                {
                    try
                    {
                        log.Info("About to authenticate...");
                        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(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
                            tradeManager.OnTimeout    += OnTradeTimeout;
                            tradeManager.OnTradeEnded += OnTradeEnded;
                            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());
                    }
                }

                if (Trade.CurrentSchema == null)
                {
                    log.Info("Downloading Schema...");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Downloading schema...";
                    }));
                    try
                    {
                        Trade.CurrentSchema = Schema.FetchSchema(apiKey);
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.ToString());
                        MessageBox.Show("I can't fetch the schema! Your API key may be invalid or there may be a problem connecting to Steam. Please make sure you have obtained a proper API key at http://steamcommunity.com/dev/apikey",
                                        "Schema Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error,
                                        MessageBoxDefaultButton.Button1);
                        main.wrongAPI = true;
                        main.Invoke((Action)(main.Dispose));
                        return;
                    }
                    log.Success("Schema Downloaded!");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Schema downloaded!";
                    }));
                }

                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!";
                }));

                IsLoggedIn  = true;
                displayName = SteamFriends.GetPersonaName();
                ConnectToGC(13540830642081628378);
                Thread.Sleep(500);
                DisconnectFromGC();
                try
                {
                    main.Invoke((Action)(main.Hide));
                }
                catch (Exception)
                {
                    Environment.Exit(1);
                }
                Thread.Sleep(2500);
                CDNCache.Initialize();
            });

            // 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

            #region Friends
            msg.Handle <SteamFriends.FriendsListCallback>(callback =>
            {
                bool newFriend = false;
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (!friends.Contains(friend.SteamID) && !friend.SteamID.ToString().StartsWith("1"))
                    {
                        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);
                                    newFriend = true;
                                    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);

                                    /*if (friend.Relationship == EFriendRelationship.RequestRecipient &&
                                     *  GetUserHandler(friend.SteamID).OnFriendAdd())
                                     * {
                                     *  SteamFriends.AddFriend(friend.SteamID);
                                     * }*/
                                    newFriend = true;
                                    string name = SteamFriends.GetFriendPersonaName(friend.SteamID);
                                    string status = SteamFriends.GetFriendPersonaState(friend.SteamID).ToString();
                                    if (!ListFriendRequests.Find(friend.SteamID))
                                    {
                                        try
                                        {
                                            showFriends.NotifyFriendRequest();
                                            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, "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);
                                            }
                                            showFriends.list_friendreq.SetObjects(ListFriendRequests.Get());
                                        }
                                        catch
                                        {
                                            Console.WriteLine("Friends list hasn't loaded yet...");
                                        }
                                    }
                                }
                            }));
                        }).Start();
                    }
                    else
                    {
                        if (friend.Relationship == EFriendRelationship.None)
                        {
                            friends.Remove(friend.SteamID);
                            GetUserHandler(friend.SteamID).OnFriendRemove();
                        }
                    }
                }
                if (!newFriend && ListFriendRequests.Get().Count == 0)
                {
                    if (showFriends != null)
                    {
                        showFriends.HideFriendRequests();
                    }
                }
            });

            msg.Handle <SteamFriends.PersonaStateCallback>(callback =>
            {
                var status = callback.State;
                var sid    = callback.FriendID;
                GetUserHandler(sid).SetStatus(status);
                ListFriends.UpdateStatus(sid, status.ToString());
            });


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

                if (callback.EntryType == EChatEntryType.Typing)
                {
                    var name = SteamFriends.GetFriendPersonaName(callback.Sender);
                    GetUserHandler(callback.Sender).SetChatStatus(name + " is typing...");
                }
                else
                {
                    GetUserHandler(callback.Sender).SetChatStatus("");
                }

                if (callback.EntryType == EChatEntryType.ChatMsg ||
                    callback.EntryType == EChatEntryType.Emote)
                {
                    //log.Info (String.Format ("Chat Message from {0}: {1}",
                    //                     SteamFriends.GetFriendPersonaName (callback.Sender),
                    //                     callback.Message
                    //));
                    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.Info ("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
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade declined. Could not correctly fetch your backpack.");

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

                if (tradeManager.OtherInventory.IsPrivate)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade declined. Your backpack cannot be private.");

                    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!");
                }
                if (callback.Response == EEconTradeResponse.Cancel ||
                    callback.Response == EEconTradeResponse.ConnectionFailed ||
                    callback.Response == EEconTradeResponse.Declined ||
                    callback.Response == EEconTradeResponse.Error ||
                    callback.Response == EEconTradeResponse.InitiatorAlreadyTrading ||
                    callback.Response == EEconTradeResponse.TargetAlreadyTrading ||
                    callback.Response == EEconTradeResponse.Timeout ||
                    callback.Response == EEconTradeResponse.TooSoon ||
                    callback.Response == EEconTradeResponse.TradeBannedInitiator ||
                    callback.Response == EEconTradeResponse.TradeBannedTarget ||
                    callback.Response == EEconTradeResponse.NotLoggedIn) // uh...
                {
                    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.Error)
                    {
                        TradeResponse(callback.OtherClient, "An error has occurred in sending the trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.InitiatorAlreadyTrading)
                    {
                        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.Timeout)
                    {
                        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 =>
            {
                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;
            }
        }
Exemplo n.º 2
0
        public void LoadFriends()
        {
            ListFriends.Clear();
            Console.WriteLine("Loading all friends...");
            for (int count = 0; count < SteamFriends.GetFriendCount(); count++)
            {
                var friendID    = SteamFriends.GetFriendByIndex(count);
                var friendName  = SteamFriends.GetFriendPersonaName(friendID);
                var friendState = SteamFriends.GetFriendPersonaState(friendID).ToString();
                if (friendState.ToString() != "Offline" && SteamFriends.GetFriendRelationship(friendID) == EFriendRelationship.Friend)
                {
                    string friend_name = friendName + " (" + friendID + ")" + Environment.NewLine + friendState;
                    ListFriends.Add(friendName, friendID, friendState);
                }
                Thread.Sleep(25);
            }
            for (int count = 0; count < SteamFriends.GetFriendCount(); count++)
            {
                var friendID    = SteamFriends.GetFriendByIndex(count);
                var friendName  = SteamFriends.GetFriendPersonaName(friendID);
                var friendState = SteamFriends.GetFriendPersonaState(friendID).ToString();
                if (friendState.ToString() == "Offline" && SteamFriends.GetFriendRelationship(friendID) == EFriendRelationship.Friend)
                {
                    ListFriends.Add(friendName, friendID, friendState);
                }
                Thread.Sleep(25);
            }
            bool newFriend = true;

            foreach (var item in ListFriends.Get())
            {
                if (ListFriendRequests.Find(item.SID))
                {
                    Console.WriteLine("Found friend {0} in list of friend requests, so let's remove the user.", item.Name);
                    // Not a friend request, so let's remove it
                    ListFriendRequests.Remove(item.SID);
                    newFriend = false;
                }
            }
            foreach (var item in ListFriendRequests.Get())
            {
                if (item.Name == "[unknown]")
                {
                    string name = SteamFriends.GetFriendPersonaName(item.SteamID);
                    ListFriendRequests.Remove(item.SteamID);
                    ListFriendRequests.Add(name, item.SteamID);
                }
                if (item.Name == "")
                {
                    string name = SteamFriends.GetFriendPersonaName(item.SteamID);
                    ListFriendRequests.Remove(item.SteamID);
                    ListFriendRequests.Add(name, item.SteamID);
                }
            }
            if (newFriend && ListFriendRequests.Get().Count != 0)
            {
                Console.WriteLine("Notifying about new friend request.");
                showFriends.NotifyFriendRequest();
                showFriends.list_friendreq.SetObjects(ListFriendRequests.Get());
            }
            Console.WriteLine("Done!");
        }