Beispiel #1
0
        /// <summary>
        /// Adds a callback to the async job's result set.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <returns><c>true</c> if this result completes the set; otherwise, <c>false</c>.</returns>
        internal override bool AddResult(CallbackMsg callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            T callbackMsg = (T)callback;

            // add this callback to our result set
            results.Add(callbackMsg);

            if (finishCondition(callbackMsg))
            {
                // if we've passed our finish condition based on this callback
                // (for instance, if steam tells us we have no more pending messages for this job)
                // then we're complete

                tcs.TrySetResult(new ResultSet {
                    Complete = true, Results = new ReadOnlyCollection <T>(results)
                });

                return(true);
            }
            else
            {
                // otherwise, we're not complete and we'll wait for the next message
                // trigger heartbeat logic to keep this job alive as it waits for the next message
                Heartbeat();

                return(false);
            }
        }
Beispiel #2
0
        void HandleDisconnected(CallbackMsg msg)
        {
            var details = msg as SteamClient.DisconnectedCallback;

            Logger.WriteLine("Disconnected from the Steam network.");
            IsRunning = false;
        }
Beispiel #3
0
        public void HandleCallback( CallbackMsg msg )
        {
            if ( !msg.IsType<SteamFriends.FriendMsgCallback>() )
                return;

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

                if ( type == EChatEntryType.ChatMsg || type == EChatEntryType.Emote || type == EChatEntryType.InviteGame )
                {
                    ChatDialog cd = GetChat( friendMsg.Sender );
                    cd.HandleChat( friendMsg );
                }
            } );

            msg.Handle<SteamFriends.PersonaStateCallback>( personaState =>
            {
                if ( personaState.FriendID == Steam3.SteamClient.SteamID )
                    return;

                ChatDialog cd = GetChat( personaState.FriendID );
                cd.HandleState( personaState );
            } );
        }
Beispiel #4
0
        void HandleSteamCallback(CallbackMsg msg)
        {
            var messageMap = new Dictionary<Type, Action<CallbackMsg>>
            {
                { typeof(SteamClient.ConnectedCallback), HandleConnected },
                { typeof(SteamClient.DisconnectedCallback), HandleDisconnected },
                    
                { typeof(SteamUser.LoggedOnCallback), HandleLoggedOn },
                { typeof(SteamUser.LoggedOffCallback), HandleLoggedOff },
                { typeof(SteamUser.LoginKeyCallback), HandleLoginKey },
                { typeof(SteamWeb.WebLoggedOnCallback), HandleWebLoggedOn },
                    
                { typeof(SteamFriends.FriendMsgCallback), HandleFriendMessage },
                { typeof(SteamFriends.FriendAddedCallback), HandleFriendAdded },
                    
                { typeof(SteamTrading.TradeRequestCallback), HandleTradeRequest },
                { typeof(SteamTrading.TradeProposedCallback), HandleTradeProposed },

                { typeof(SteamGameCoordinator.MessageCallback), HandleGCMessage },
            };

            Action<CallbackMsg> func;
            if (!messageMap.TryGetValue(msg.GetType(), out func))
                return;

            func(msg);
        }
Beispiel #5
0
        void HandleLoginKey(CallbackMsg msg)
        {
            var details = msg as SteamUser.LoginKeyCallback;
            //Logger.WriteLine("Login Key: " + details.LoginKey);

            Logger.WriteLine("Logging to the Steam Web network...");
            SteamWeb.LogOn(details);
        }
Beispiel #6
0
        void HandleLoggedOn(CallbackMsg msg)
        {
            var details = msg as SteamUser.LoggedOnCallback;
            Logger.WriteLine("Logged on: " + details.Result);

            Logger.WriteLine("Launching TF2...");
            ConnectToGC(TF2App);
        }
Beispiel #7
0
        public void HandleCallback(CallbackMsg msg)
        {
            if(msg.IsType<SteamUser.LoginKeyCallback>())
            {
                GetClient().Friends.SetPersonaState(EPersonaState.Online);

                Friend.Me = new Friend(GetClient().User.GetSteamID());
                Friend.Me.Name = "me";

                SteamAlerts.ShowToast("Connected to Steam");
            }
            else if (msg.IsType<SteamUser.LogOnCallback>())
            {
                SteamUser.LogOnCallback callback = (SteamUser.LogOnCallback)msg;

                if (callback.Result == EResult.OK)
                {
                    EnableAutoReconnect();
                }
                else
                {
                    DisableAutoReconnect();
                }
            }
            else if (msg.IsType<SteamFriends.FriendMsgCallback>())
            {
                SteamFriends.FriendMsgCallback callback = (SteamFriends.FriendMsgCallback)msg;

                if (callback.EntryType == EChatEntryType.ChatMsg)
                {
                    Friend friend = Friend.GetFriendBySteamId(callback.Sender.ToString());

                    if (friend != activeChat)
                    {
                        Intent intent = new Intent(SteamAlerts.GetContext(), typeof(Chat));
                        intent.SetAction("chat_notification_" + DateTime.Now.Ticks);
                        intent.PutExtra("steam_id", friend.SteamId.ToString());

                        SteamAlerts.Notification("Message from " + friend.Name, friend.Name + ": " + callback.Message, callback.Message, intent, "steam_id", friend.SteamId.ToString());
                        SteamAlerts.PlaySound();
                        SteamAlerts.Vibrate(400);
                    }
                }
            }
            else if (msg.IsType<SteamClient.ConnectCallback>())
            {
                SteamAlerts.Notification("Steam Droid", "Connected to Steam", "Connected to Steam", new Intent(SteamAlerts.GetContext(), typeof(Main)), null, null);
            }
            else if (msg.IsType<SteamClient.DisconnectCallback>())
            {
                SteamAlerts.Notification("Steam Droid", "Disconnected from Steam", "Connected to Steam", new Intent(SteamAlerts.GetContext(), typeof(Main)), null, null);
                SteamAlerts.ShowToast("Disconnected from Steam");
            }
        }
Beispiel #8
0
        /// <summary>
        /// Posts a callback to the queue. This is normally used directly by client message handlers.
        /// </summary>
        /// <param name="msg">The message.</param>
        public void PostCallback(CallbackMsg msg)
        {
            if (msg == null)
            {
                return;
            }

            lock ( callbackLock )
            {
                callbackQueue.Enqueue(msg);
                Monitor.Pulse(callbackLock);
            }
        }
        public void HandleCallback(CallbackMsg msg)
        {
            if (msg.IsType<SteamClient.ConnectCallback>())
            {
                Logger.Get().Log("[Callback] Connected");
            }
            else if (msg.IsType<SteamClient.DisconnectCallback>())
            {
                Logger.Get().Log("[Callback] Disconnected");
                IsAuthorized = false;
                Send(Protocol.Server.LoggedOut);
            }
            else if (msg.IsType<SteamUser.LogOnCallback>())
            {
                SteamUser.LogOnCallback callback = (SteamUser.LogOnCallback)msg;

                Logger.Get().Log("[Callback] Logon: " + callback.Result + "/" + callback.ExtendedResult);

                if (callback.Result == EResult.AccountLogonDenied || callback.Result == EResult.InvalidLoginAuthCode)
                {
                    Send(Protocol.Server.AuthRequest);
                    IsAuthorized = true;
                }

                if (callback.Result == EResult.OK)
                {
                    IsAuthorized = true;
                }
            }
            else if (msg.IsType<SteamUser.LoginKeyCallback>())
            {
                Logger.Get().Log("[Callback] Logged in, setting persona state to online");

                steam.Friends.SetPersonaState(SteamKit2.EPersonaState.Online);

                Send(Protocol.Server.LoggedIn);
            }
            else if (msg.IsType<SteamFriends.FriendMsgCallback>())
            {
                SteamFriends.FriendMsgCallback chat = (SteamFriends.FriendMsgCallback)msg;
                if (chat.EntryType == EChatEntryType.ChatMsg)
                {
                    Send(Protocol.Server.ChatReceived, chat.Sender.ToString(), chat.Message);
                }
            }
            else if (msg.IsType<SteamFriends.PersonaStateCallback>())
            {
                SteamFriends.PersonaStateCallback friend = (SteamFriends.PersonaStateCallback)msg;
                Send(Protocol.Server.FriendStateChanged, friend.FriendID.ToString(), friend.State.ToString(), friend.GameName);
            }
        }
Beispiel #10
0
        public void HandleCallback( CallbackMsg msg )
        {
            if ( msg.IsType<SteamFriends.PersonaStateCallback>() )
            {
                var perState = ( SteamFriends.PersonaStateCallback )msg;

                if ( this.Friend == null )
                    return;

                if ( perState.FriendID != this.Friend.SteamID )
                    return;

                this.UpdateFriend( this.Friend );
            }
        }
Beispiel #11
0
        /// <summary>
        /// Posts a callback to the queue. This is normally used directly by client message handlers.
        /// </summary>
        /// <param name="msg">The message.</param>
        public void PostCallback(CallbackMsg msg)
        {
            if (msg == null)
            {
                return;
            }

            lock ( callbackLock )
            {
                callbackQueue.Enqueue(msg);
                Monitor.Pulse(callbackLock);
            }

            jobManager.TryCompleteJob(msg.JobID, msg);
        }
Beispiel #12
0
        void HandleWebLoggedOn(CallbackMsg msg)
        {
            var details = msg as SteamWeb.WebLoggedOnCallback;

            if (details.Result != EResult.OK)
            {
                Logger.WriteLine("Could not login to Web.");
                return;
            }

            Logger.WriteLine("Logged in to web successfully.");

            if (OnWebLoggedOn != null)
                OnWebLoggedOn(this);
        }
Beispiel #13
0
        void HandleServiceMethodResponse(IPacketMsg packetMsg)
        {
            CallbackMsg callback = null;

            var jobId = packetMsg.TargetJobID;

            if (_clientFileDownloadJobs.Contains(jobId))
            {
                lock (_clientFileDownloadJobs)
                {
                    _clientFileDownloadJobs.Remove(jobId);
                }

                var shareResponse = new ClientMsgProtobuf <CCloud_ClientFileDownload_Response>(packetMsg);

                callback = new ClientFileDownloadCallback(shareResponse.TargetJobID, shareResponse.Body);
            }
            else if (_clientBeginFileUploadJobs.Contains(jobId))
            {
                lock (_clientBeginFileUploadJobs)
                {
                    _clientBeginFileUploadJobs.Remove(jobId);
                }

                var shareResponse = new ClientMsgProtobuf <CCloud_ClientBeginFileUpload_Response>(packetMsg);

                callback = new ClientBeginFileUploadCallback(shareResponse.TargetJobID, shareResponse.Body);
            }
            else if (_clientCommitFileJobs.Contains(jobId))
            {
                lock (_clientCommitFileJobs)
                {
                    _clientCommitFileJobs.Remove(jobId);
                }

                var shareResponse = new ClientMsgProtobuf <CCloud_ClientCommitFileUpload_Response>(packetMsg);

                callback = new ClientCommitFileUploadCallback(shareResponse.TargetJobID, shareResponse.Body);
            }

            if (callback != null)
            {
                Client.PostCallback(callback);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Passes a callback to a pending async job.
        /// If the given callback completes the job, the job is removed from this manager.
        /// </summary>
        /// <param name="jobId">The JobID.</param>
        /// <param name="callback">The callback.</param>
        public void TryCompleteJob(JobID jobId, CallbackMsg callback)
        {
            var asyncJob = GetJob(jobId);

            if (asyncJob == null)
            {
                // not a job we are tracking ourselves, can ignore it
                return;
            }

            // pass this callback into the job so it can determine if the job is finished (in the case of multiple responses to a job)
            bool jobFinished = asyncJob.AddResult(callback);

            if (jobFinished)
            {
                // if the job is finished, we can stop tracking it
                asyncJobs.TryRemove(jobId, out _);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Passes a callback to a pending async job.
        /// If the given callback completes the job, the job is removed from this manager.
        /// </summary>
        /// <param name="jobId">The JobID.</param>
        /// <param name="callback">The callback.</param>
        public void TryCompleteJob( JobID jobId, CallbackMsg callback )
        {
            AsyncJob asyncJob = GetJob( jobId );

            if ( asyncJob == null )
            {
                // not a job we are tracking ourselves, can ignore it
                return;
            }

            // pass this callback into the job so it can determine if the job is finished (in the case of multiple responses to a job)
            bool jobFinished = asyncJob.AddResult( callback );

            if ( jobFinished )
            {
                // if the job is finished, we can stop tracking it
                asyncJobs.TryRemove( jobId, out asyncJob );
            }
        }
        public void HandleCallback( CallbackMsg msg )
        {
            if ( !msg.IsType<SteamFriends.FriendMsgCallback>() )
                return;

            var friendMsg = ( SteamFriends.FriendMsgCallback )msg;

            EChatEntryType type = friendMsg.EntryType;

            if ( type == EChatEntryType.ChatMsg || type == EChatEntryType.Emote )
            {
                if (friendMsg.Message == "Away")
                    Steam3.SteamFriends.SetPersonaState(EPersonaState.Away);
                else if (friendMsg.Message == "Busy")
                    Steam3.SteamFriends.SetPersonaState(EPersonaState.Busy);
                else if (friendMsg.Message == "Online")
                    Steam3.SteamFriends.SetPersonaState(EPersonaState.Online);

                int messageType = 2;
                if (type == EChatEntryType.Emote)
                    messageType = 3;

                if(friendMsg.Message == "Away")
                    Steam3.SteamFriends.SetPersonaState(EPersonaState.Away);
                else if(friendMsg.Message == "Busy")
                    Steam3.SteamFriends.SetPersonaState(EPersonaState.Busy);
                else if(friendMsg.Message == "Online")
                    Steam3.SteamFriends.SetPersonaState(EPersonaState.Online);

                string steamMessage = System.Text.RegularExpressions.Regex.Replace(friendMsg.Message, "<", "&lt;");
                steamMessage = System.Text.RegularExpressions.Regex.Replace(steamMessage, ">", "&gt;");

                FriendMessageData messageObject = new FriendMessageData
                {
                    SID = friendMsg.Sender.ToString(),
                    N = Steam3.SteamFriends.GetFriendPersonaName(friendMsg.Sender),
                    M = steamMessage
                };
                string messageJson = JsonConvert.SerializeObject(messageObject);

                Program.communicator.SendClientMessage(messageType, messageJson);
            }
        }
Beispiel #17
0
        public void HandleCallback(CallbackMsg msg)
        {
            if(msg.IsType<SteamClient.ConnectCallback>())
            {
                int retryCount = SteamService.GetClient().GetRetryCount();
                String retries = (retryCount > 0) ? " (retry " + retryCount + ")" : "";
                SteamAlerts.ShowProgressDialog("Connecting", "Logging in..." + retries, this);
            }
            else if(msg.IsType<SteamUser.LogOnCallback>())
            {
                SteamUser.LogOnCallback callback = (SteamUser.LogOnCallback)msg;

                if(callback.Result == EResult.AccountLogonDenied)
                {
                    RequestAuthKey();
                }
                else if(callback.Result == EResult.InvalidLoginAuthCode)
                {
                    InvalidAuthKey();
                }
                else if(callback.Result == EResult.InvalidPassword)
                {
                    SteamAlerts.ShowAlertDialog("Invalid credentials", "Invalid username or password", this);
                }
                else if(callback.Result == EResult.AlreadyLoggedInElsewhere)
                {
                    SteamAlerts.ShowAlertDialog("Already logged in", "This Steam account is already logged in elsewhere", this);
                }
            }
            else if(msg.IsType<SteamUser.LoggedOffCallback>())
            {
                SteamUser.LoggedOffCallback callback = (SteamUser.LoggedOffCallback)msg;

                if(callback.Result == EResult.InvalidProtocolVer)
                {
                    SteamAlerts.ShowAlertDialog("Error", "Invalid protocol version", this);
                }
            }

            UpdateButtons();
        }
Beispiel #18
0
 void Handle(CallbackMsg call)
 {
     registeredCallbacks
     .FindAll(callback => callback.CallbackType == call.GetType()) // find handlers interested in this callback
     .ForEach(callback => callback.Run(call));                     // run them
 }
 void PostAndRunCallback(CallbackMsg callback)
 {
     client.PostCallback(callback);
     mgr.RunCallbacks();
 }
Beispiel #20
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            #region Login
            msg.Handle<SteamClient.ConnectedCallback> (callback =>
            {
                //PrintConsole ("Connection Callback: " + callback.Result, ConsoleColor.Magenta);
                log.Debug ("Connection Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    SteamUser.LogOn (new SteamUser.LogOnDetails
                         {
                        Username = Username,
                        Password = Password,
                        AuthCode = AuthCode
                    });
                }
                else
                {
                    log.Error ("Failed to connect to Steam Community, trying again...");
                    //PrintConsole ("Failed to Connect to the steam community!\n", ConsoleColor.Red);
                    SteamClient.Connect ();
                }

            });

            msg.Handle<SteamUser.LoggedOnCallback> (callback =>
            {
                log.Debug ("Logged On Callback: " + callback.Result);
                //PrintConsole ("Logged on callback: " + callback.Result, ConsoleColor.Magenta);

                if (callback.Result != EResult.OK)
                {
                    log.Error ("Login Error: " + callback.Result);
                    //PrintConsole("Login Failure: " + callback.Result, ConsoleColor.Red);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    //PrintConsole("This account is protected by Steam Guard. Enter the authentication code sent to the associated email address", ConsoleColor.DarkYellow);
                    log.Interface ("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    AuthCode = Console.ReadLine();
                }
            });

            msg.Handle<SteamUser.LoginKeyCallback> (callback =>
            {
                while (true)
                {
                    if (Authenticate (callback))
                    {
                        log.Success ("User Authenticated!");
                        //PrintConsole ("Authenticated.");
                        break;
                    }
                    else
                    {
                        log.Warn ("Authentication failed, retrying in 2s...");
                        //PrintConsole ("Retrying auth...", ConsoleColor.Red);
                        Thread.Sleep (2000);
                    }
                }

                //PrintConsole ("Downloading schema...", ConsoleColor.Magenta);
                log.Info ("Downloading Schema...");

                Trade.CurrentSchema = Schema.FetchSchema (apiKey);

                //PrintConsole ("All Done!", ConsoleColor.Magenta);
                log.Success ("Schema Downloaded!");

                SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
                SteamFriends.SetPersonaState (EPersonaState.LookingToTrade);

                log.Success ("Steam Bot Logged In Completely!");
                //PrintConsole ("Successfully Logged In!\nWelcome " + SteamUser.SteamID + "\n\n", ConsoleColor.Magenta);

                IsLoggedIn = true;
            });
            #endregion

            #region Friends
            msg.Handle<SteamFriends.PersonaStateCallback> (callback =>
            {
                SteamFriends.AddFriend (callback.FriendID);
            });

            msg.Handle<SteamFriends.FriendMsgCallback> (callback =>
            {
                //Type (emote or chat)
                EChatEntryType type = callback.EntryType;

                if (type == EChatEntryType.ChatMsg)
                {
                    log.Info (String.Format ("Chat Message from {0}: {1}",
                                             SteamFriends.GetFriendPersonaName (callback.Sender),
                                             callback.Message
                                             ));
                    //PrintConsole ("[Chat] " + SteamFriends.GetFriendPersonaName (callback.Sender) + ": " + callback.Message, ConsoleColor.Magenta);

                    //string message = callback.Message;

                    string response = ChatResponse;
                    SteamFriends.SendChatMessage (callback.Sender, EChatEntryType.ChatMsg, response);
                }

            });
            #endregion

            #region Trading
            msg.Handle<SteamTrading.TradeStartSessionCallback> (call =>
            {
                CurrentTrade = new Trade (SteamUser.SteamID, call.Other, sessionId, token, apiKey, this, TradeListener);
                CurrentTrade.MaximumTradeTime = MaximumTradeTime;
                CurrentTrade.MaximumActionGap = MaximiumActionGap;
                CurrentTrade.OnTimeout += () => {
                    CurrentTrade = null;
                };
            });

            msg.Handle<SteamTrading.TradeCancelRequestCallback> (call =>
            {
                log.Info ("Cancel Callback Request detected");
                CurrentTrade = null;
            });

            msg.Handle<SteamTrading.TradeProposedCallback> (thing =>
            {
                SteamTrade.RequestTrade (thing.Other);
            });

            msg.Handle<SteamTrading.TradeRequestCallback> (thing =>
            {
                log.Debug ("Trade Status: "+ thing.Status);
                //PrintConsole ("Trade Status: " + thing.Status, ConsoleColor.Magenta);

                if (thing.Status == ETradeStatus.Accepted)
                {
                    log.Info ("Trade Accepted!");
                    //PrintConsole ("Trade accepted!", ConsoleColor.Magenta);
                }

                if (thing.Status == ETradeStatus.Cancelled)
                {
                    log.Info ("Trade was cancelled");
                    CurrentTrade = null;
                }
            });
            #endregion

            #region Disconnect
            msg.Handle<SteamUser.LoggedOffCallback> (callback =>
            {
                IsLoggedIn = false;
                log.Warn ("Logged Off: " + callback.Result);
                //PrintConsole ("[SteamRE] Logged Off: " + callback.Result, ConsoleColor.Magenta);
            });

            msg.Handle<SteamClient.DisconnectedCallback> (callback =>
            {
                IsLoggedIn = false;
                if (CurrentTrade != null)
                {
                    CurrentTrade = null;
                }
                log.Warn ("Disconnected from Steam Network!");
                //PrintConsole ("[SteamRE] Disconnected from Steam Network!", ConsoleColor.Magenta);
                SteamClient.Connect ();
            });
            #endregion
        }
Beispiel #21
0
        public void HandleCallback(CallbackMsg msg)
        {
            if(msg.IsType<SteamFriends.FriendMsgCallback>())
            {
                SteamFriends.FriendMsgCallback callback = (SteamFriends.FriendMsgCallback)msg;

                if(callback.EntryType == EChatEntryType.ChatMsg && callback.Sender == friend.SteamId)
                {
                    ChatMessage message = new ChatMessage(friend, callback.Message);
                    Add(message);
                    NotifyDataSetChanged();
                }
            }
        }
Beispiel #22
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...");
                    SteamClient.Connect ();
                }

            });

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

                if (callback.Result != EResult.OK)
                {
                    log.Error ("Login Error: " + callback.Result);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command.");

                    // try to get the steamguard auth code from the event callback
                    var eva = new SteamGuardRequiredEventArgs();
                    FireOnSteamGuardRequired(eva);
                    if (!String.IsNullOrEmpty(eva.SteamGuard))
                        logOnDetails.AuthCode = eva.SteamGuard;
                    else
                        logOnDetails.AuthCode = Console.ReadLine();
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
                    logOnDetails.AuthCode = Console.ReadLine();
                }
            });

            msg.Handle<SteamUser.LoginKeyCallback> (callback =>
            {
                while (true)
                {
                    bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token);
                    if (authd)
                    {
                        log.Success ("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...");
                        Thread.Sleep (2000);
                    }
                }

                if (Trade.CurrentSchema == null)
                {
                    log.Info ("Downloading Schema...");
                    Trade.CurrentSchema = Schema.FetchSchema (apiKey);
                    log.Success ("Schema Downloaded!");
                }

                SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
                SteamFriends.SetPersonaState (EPersonaState.Online);

                log.Success ("Steam Bot Logged In Completely!");

                IsLoggedIn = true;
            });

            // 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 =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (!friends.Contains(friend.SteamID))
                    {
                        friends.Add(friend.SteamID);
                        if (friend.Relationship == EFriendRelationship.PendingInvitee &&
                            GetUserHandler(friend.SteamID).OnFriendAdd())
                        {
                            SteamFriends.AddFriend(friend.SteamID);
                        }
                    }
                    else
                    {
                        if (friend.Relationship == EFriendRelationship.None)
                        {
                            friends.Remove(friend.SteamID);
                            GetUserHandler(friend.SteamID).OnFriendRemove();
                        }
                    }
                }
            });

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

                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);
                }
            });
            #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
                {
                    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 ())
                    SteamTrade.RespondToTrade (callback.TradeID, true);
                else
                    SteamTrade.RespondToTrade (callback.TradeID, false);
            });

            msg.Handle<SteamTrading.TradeResultCallback> (callback =>
            {
                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    log.Debug ("Trade Status: " + callback.Response);
                    log.Info ("Trade Accepted!");
                }
                else
                {
                    log.Warn ("Trade failed: " + callback.Response);
                    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!");
                SteamClient.Connect ();
            });
            #endregion
        }
Beispiel #23
0
 /// <summary>
 /// Adds a callback to the async job's result set.
 /// </summary>
 /// <param name="callback">The callback.</param>
 /// <returns><c>true</c> if this result completes the set; otherwise, <c>false</c>.</returns>
 internal abstract bool AddResult(CallbackMsg callback);
Beispiel #24
0
Datei: Bot.cs Projekt: Jamyn/Mist
        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)
                {
                    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 =>
            {
                while (true)
                {
                    log.Info ("About to authenticate...");
                    bool authd = false;
                    try
                    {
                        authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token);
                    }
                    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);
                    }
                }

                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.Close));
                        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();
                try
                {
                    main.Invoke((Action)(main.Hide));
                }
                catch (Exception)
                {
                    Environment.Exit(1);
                }
                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;
            }
        }
Beispiel #25
0
 /// <summary>
 /// Pushes a callback to registered handlers
 /// </summary>
 /// <param name="msg">The callback to push</param>
 private void Push(CallbackMsg msg)
 {
     foreach (ICallbackHandler handler in callbackHandlers)
     {
         handler.HandleCallback(msg);
     }
 }
Beispiel #26
0
 internal CallbackEventArgs(CallbackMsg msg)
 {
     this.msg = msg;
 }
Beispiel #27
0
        public void HandleCallback( CallbackMsg msg )
        {
            if ( msg.IsType<SteamFriends.PersonaStateCallback>() )
            {
                var perState = ( SteamFriends.PersonaStateCallback )msg;

                if ( perState.FriendID == selfControl.Friend.SteamID )
                {
                    selfControl.UpdateFriend( selfControl.Friend );

                    suppressStateMsg = true;
                    stateComboBox.SelectedIndex = GetIndexFromState( perState.State );
                    suppressStateMsg = false;

                    return;
                }

                nextSort = DateTime.Now + TimeSpan.FromSeconds( 0.1 );
                sortTimer.Start();
            }

            if ( msg.IsType<SteamUser.LoggedOffCallback>() )
            {
                var callback = ( SteamUser.LoggedOffCallback )msg;

                Util.MsgBox( this, string.Format( "Logged off from Steam3: {0}", callback.Result ) );

                this.Relog = true;
                this.Close();

                return;
            }

            if ( msg.IsType<SteamFriends.FriendsListCallback>() )
            {
                selfControl.UpdateFriend( new Friend( Steam3.SteamUser.SteamID ) );
                this.UpdateFriends();
            }

            if ( msg.IsType<SteamUser.LoginKeyCallback>() )
            {
                Steam3.SteamFriends.SetPersonaState( EPersonaState.Online );
                this.Enabled = true;
            }

            if ( msg.IsType<SteamUser.LoggedOnCallback>() )
            {
                var logOnResp = ( SteamUser.LoggedOnCallback )msg;

                if ( logOnResp.Result == EResult.AccountLogonDenied )
                {
                    expectDisconnect = true;

                    SteamGuardDialog sgDialog = new SteamGuardDialog();

                    if ( sgDialog.ShowDialog( this ) != DialogResult.OK )
                    {
                        this.Relog = true;
                        this.Close();

                        return;
                    }

                    Steam3.AuthCode = sgDialog.AuthCode;

                    // if we got this logon response, we got disconnected, so lets reconnect
                    try
                    {
                        Steam3.Connect();
                    }
                    catch ( Steam3Exception ex )
                    {
                        Util.MsgBox( this, string.Format( "Unable to connect to Steam3: {0}", ex.Message ) );

                        this.Relog = true;
                        this.Close();

                        return;
                    }
                }
                else if ( logOnResp.Result != EResult.OK )
                {
                    Util.MsgBox( this, string.Format( "Unable to login to Steam3. Result code: {0}", logOnResp.Result ) );

                    this.Relog = true;
                    this.Close();

                    return;
                }
            }

            if ( msg.IsType<SteamFriends.FriendAddedCallback>() )
            {
                var friendAdded = ( SteamFriends.FriendAddedCallback )msg;

                if ( friendAdded.Result != EResult.OK )
                {
                    Util.MsgBox( this, "Unable to add friend! Result: " + friendAdded.Result );
                }
            }

            msg.Handle<SteamClient.DisconnectedCallback>( ( callback ) =>
            {
                // if we expected this disconnection (cause of steamguard), we do nothing
                if ( expectDisconnect )
                {
                    expectDisconnect = false;
                    return;
                }

                Util.MsgBox( this, "Disconnected from Steam3!" );

                this.Relog = true;
                this.Close();

                return;
            } );
        }
Beispiel #28
0
        /// <summary>
        /// Posts a callback to the queue. This is normally used directly by client message handlers.
        /// </summary>
        /// <param name="msg">The message.</param>
#if STATIC_CALLBACKS
        public static void PostCallback(CallbackMsg msg)
        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...");
                    SteamClient.Connect ();
                }

            });

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

                if (callback.Result == EResult.OK)
                {
                    MyLoginKey = callback.WebAPIUserNonce;
                }
                else
                {
                    log.Error ("Login Error: " + callback.Result);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command.");

                    // try to get the steamguard auth code from the event callback
                    var eva = new SteamGuardRequiredEventArgs();
                    FireOnSteamGuardRequired(eva);
                    if (!String.IsNullOrEmpty(eva.SteamGuard))
                        logOnDetails.AuthCode = eva.SteamGuard;
                    else
                        logOnDetails.AuthCode = Console.ReadLine();
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
                    logOnDetails.AuthCode = Console.ReadLine();
                }
            });

            msg.Handle<SteamUser.LoginKeyCallback> (callback =>
            {
                while (true)
                {
                    bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey);

                    if (authd)
                    {
                        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);
                        log.Success ("User Authenticated!");
                        BotSteamIds.Add(SteamUser.SteamID);

                        tradeManager = new TradeManager(apiKey, sessionId, token);
                        tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
                        tradeManager.OnTimeout += OnTradeTimeout;
                        break;
                    }
                    else
                    {
                        log.Warn ("Authentication failed, retrying in 2s...");
                        Thread.Sleep (2000);
                    }
                }

                SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
                SteamFriends.SetPersonaState (EPersonaState.Online);

                log.Success ("Steam Bot Logged In Completely!");

                IsLoggedIn = true;

                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);

                Pusher = new Pusher("51a9410427d703c5a743");
                Pusher.Connected += Pusher_Connected;
                Pusher.Connect();

                GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
            });

            // 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 =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (friend.SteamID.AccountType == EAccountType.Clan)
                    {
                        if (!groups.Contains(friend.SteamID))
                        {
                            groups.Add(friend.SteamID);
                            if (friend.Relationship == EFriendRelationship.RequestRecipient)
                            {
                                if (GetUserHandler(friend.SteamID).OnGroupAdd())
                                {
                                    AcceptGroupInvite(friend.SteamID);
                                }
                                else
                                {
                                    DeclineGroupInvite(friend.SteamID);
                                }
                            }
                        }
                        else
                        {
                            if (friend.Relationship == EFriendRelationship.None)
                            {
                                groups.Remove(friend.SteamID);
                            }
                        }
                    }
                    else if (friend.SteamID.AccountType != EAccountType.Clan)
                    {
                    if (!friends.Contains(friend.SteamID))
                    {
                        friends.Add(friend.SteamID);
                        if (friend.Relationship == EFriendRelationship.RequestRecipient &&
                            GetUserHandler(friend.SteamID).OnFriendAdd())
                        {
                            SteamFriends.AddFriend(friend.SteamID);
                        }
                    }
                    else
                    {
                        if (friend.Relationship == EFriendRelationship.None)
                        {
                            friends.Remove(friend.SteamID);
                            GetUserHandler(friend.SteamID).OnFriendRemove();
                        }
                    }
                }
                }
            });


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

                if (callback.EntryType == EChatEntryType.ChatMsg)
                {
                    log.Info (String.Format ("Chat Message from {0}: {1}",
                                         SteamFriends.GetFriendPersonaName (callback.Sender),
                                         callback.Message
                                         ));
                    GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
                }
            });
            #endregion

            #region Group Chat
            msg.Handle<SteamFriends.ChatMsgCallback>(callback =>
            {
                GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, 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 (WebException we)
                {                 
                    SteamFriends.SendChatMessage(callback.OtherClient,
                             EChatEntryType.ChatMsg,
                             "Trade error: " + we.Message);

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }
                catch (Exception)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                             EChatEntryType.ChatMsg,
                             "Trade declined. Could not correctly fetch your backpack.");

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

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

            msg.Handle<SteamTrading.TradeResultCallback> (callback =>
            {
                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    log.Debug ("Trade Status: " + callback.Response);
                    log.Info ("Trade Accepted!");
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString());
                }
                else
                {
                    log.Warn ("Trade failed: " + callback.Response);
                    CloseTrade ();
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString());
                }

            });
            #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!");
                SteamClient.Connect ();
            });
            #endregion
        }
        public void HandleCallback(CallbackMsg msg)
        {
            if (msg.IsType<SteamFriends.PersonaStateCallback>())
            {
                var perState = (SteamFriends.PersonaStateCallback)msg;

                if (perState.AvatarHash != null && !IsZeros(perState.AvatarHash))
                {
                    CDNCache.DownloadAvatar(perState.FriendID, perState.AvatarHash, new Action<AvatarDownloadDetails>(delegate(AvatarDownloadDetails details) { }));
                }

                //Add logged in user data
                if (perState.FriendID == Steam3.SteamUser.GetSteamID())
                {
                    byte[] avatarHash = CDNCache.GetAvatarHash(perState.FriendID);
                    string avatarUrl = "http://media.steampowered.com/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg";

                    if (avatarHash != null)
                        avatarUrl = CDNCache.GetAvatarUrl(avatarHash);

                    string playerState = Steam3.SteamFriends.GetPersonaState().ToString();
                    string gamePlayedName = Steam3.SteamFriends.GetFriendGamePlayedName(Steam3.SteamUser.GetSteamID());
                    if (!String.IsNullOrEmpty(gamePlayedName))
                        playerState = "Playing " + gamePlayedName;
                    else
                        playerState = Steam3.SteamFriends.GetPersonaState().ToString();

                    string steamName = Steam3.SteamFriends.GetPersonaName();
                    if (steamName.Length > 22)
                        steamName = steamName.Substring(0, 22);

                    int stateID = 99;
                    switch (Steam3.SteamFriends.GetPersonaState())
                    {
                        case EPersonaState.Online:
                            stateID = 2;
                            break;
                        case EPersonaState.Away:
                            stateID = 3;
                            break;
                        case EPersonaState.Busy:
                            stateID = 4;
                            break;
                        case EPersonaState.Snooze:
                            stateID = 5;
                            break;
                        case EPersonaState.Offline:
                            stateID = 6;
                            break;
                    }

                    SteamUserData messageObject = new SteamUserData
                    {
                        SID = Steam3.SteamUser.GetSteamID().ToString(),
                        N = steamName,
                        A = avatarUrl,
                        St = playerState,
                        StID = stateID
                    };
                    string messageJson = JsonConvert.SerializeObject(messageObject);

                    Program.communicator.SendClientMessage(1, messageJson);
                }
                else
                {
                    List<SteamUserData> friends = new List<SteamUserData>();

                    for (int i = 0; i < Steam3.SteamFriends.GetFriendCount(); i++)
                    {
                        SteamID friendID = Steam3.SteamFriends.GetFriendByIndex(i);

                        byte[] avatarHash = CDNCache.GetAvatarHash(friendID);
                        string avatarUrl = "http://media.steampowered.com/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg";

                        if (avatarHash != null)
                            avatarUrl = CDNCache.GetAvatarUrl(avatarHash);

                        string playerState = Steam3.SteamFriends.GetFriendPersonaState(friendID).ToString();
                        string gamePlayedName = Steam3.SteamFriends.GetFriendGamePlayedName(friendID);

                        int stateID = 99;
                        switch (Steam3.SteamFriends.GetFriendPersonaState(friendID))
                        {
                            case EPersonaState.Online:
                                stateID = 2;
                                break;
                            case EPersonaState.Away:
                                stateID = 3;
                                break;
                            case EPersonaState.Busy:
                                stateID = 4;
                                break;
                            case EPersonaState.Snooze:
                                stateID = 5;
                                break;
                            case EPersonaState.Offline:
                                stateID = 6;
                                break;
                        }

                        if (!String.IsNullOrEmpty(gamePlayedName))
                        {
                            playerState = "Playing " + gamePlayedName;
                            stateID = 1;
                        }
                        else
                            playerState = Steam3.SteamFriends.GetFriendPersonaState(friendID).ToString();

                        if (Steam3.SteamFriends.GetFriendRelationship(friendID) == EFriendRelationship.Blocked)
                        {
                            playerState = "Blocked";
                            stateID = 6;
                        }

                        string steamName = Steam3.SteamFriends.GetFriendPersonaName(friendID);
                        if (steamName.Length > 22)
                            steamName = steamName.Substring(0, 22);

                        SteamUserData messageObject = new SteamUserData
                        {
                            SID = friendID.ToString(),
                            N = steamName,
                            A = avatarUrl,
                            St = playerState,
                            StID = stateID
                        };

                        friends.Add(messageObject);
                    }

                    friends = friends.OrderBy(d => d.StID).ThenBy(d => d.N).ToList();
                    string messageJson = JsonConvert.SerializeObject(friends);

                    Program.communicator.SendClientMessage(4, messageJson);
                }
            }

            if (msg.IsType<SteamUser.LoggedOffCallback>())
            {
                SteamUser.LoggedOffCallback callback = (SteamUser.LoggedOffCallback)msg;

                Program.Shutdown("you were logged off");

                return;
            }

            if (msg.IsType<SteamFriends.FriendsListCallback>())
            {
                Steam3.SteamFriends.SetPersonaState(EPersonaState.Online); //Necesary because steam sometimes forgets to send the login key
            }

            if (msg.IsType<SteamUser.LogOnCallback>())
            {
                var logOnResp = (SteamUser.LogOnCallback)msg;

                if (logOnResp.Result == EResult.OK)
                {
                    try
                    {
                        //Update the session with the status! (is this really needed anymore?)
                        MySqlCommand command = new MySqlCommand();
                        command.CommandText = "UPDATE sessions SET Status=@Status WHERE SessionToken=@SessionToken";
                        command.Parameters.AddWithValue("@Status", 2);
                        command.Parameters.AddWithValue("@SessionToken", Program.sessionToken);
                        Database.Command(command);
                        command.Dispose();

                        //Lets update the users section
                        command = new MySqlCommand();
                        command.CommandText = "SELECT COUNT(*) FROM users WHERE Username=@Username";
                        command.Parameters.AddWithValue("@Username", Program.userName);
                        Int64 rows = Database.CountCommand(command);
                        command.Dispose();

                        if (rows == 0)
                        {
                            //New user - lets add 'em
                            double currentTime = CommonCommunicator.UnixTime();
                            int hasSteamGuard = Program.steamGuardKey != "" && Program.steamGuardKey != null ? 1:0; //AMAZING SHORTHAND

                            command = new MySqlCommand();
                            command.CommandText = "INSERT INTO users (Username, SteamID, SteamGuard, TimesLogin, LastLogin, FirstLogin) VALUES (@Username, @SteamID, @SteamGuard, @TimesLogin, @LastLogin, @FirstLogin);";
                            command.Parameters.AddWithValue("@Username", Program.userName);
                            command.Parameters.AddWithValue("@SteamID", Steam3.SteamUser.GetSteamID().ToString());
                            command.Parameters.AddWithValue("@SteamGuard", hasSteamGuard);
                            command.Parameters.AddWithValue("@TimesLogin", 1);
                            command.Parameters.AddWithValue("@LastLogin", currentTime);
                            command.Parameters.AddWithValue("@FirstLogin", currentTime);

                            Database.Command(command);
                            command.Dispose();
                        }
                        else
                        {
                            //Update user
                            double currentTime = CommonCommunicator.UnixTime();

                            command = new MySqlCommand();
                            command.CommandText = "UPDATE users SET TimesLogin=TimesLogin+1, LastLogin=@LastLogin WHERE Username=@Username";
                            command.Parameters.AddWithValue("@Username", Program.userName);
                            command.Parameters.AddWithValue("@LastLogin", currentTime);

                            Database.Command(command);
                            command.Dispose();
                        }

                        Program.steamConnectionReply = "Success";
                    }
                    catch
                    {
                        Program.Shutdown("Can not update DB session");
                    }
                }
                else if (logOnResp.Result == EResult.InvalidPassword)
                {
                    Steam3.Shutdown();
                    Program.steamConnectionReply = "Invalid";
                    Steam3.RemoveHandler(this);
                    Program.Shutdown("Invalid");
                }
                else if (logOnResp.Result == EResult.AccountLogonDenied || logOnResp.Result == EResult.InvalidLoginAuthCode)
                {
                    Steam3.Shutdown();
                    Program.steamConnectionReply = "SteamGuard";
                    Steam3.RemoveHandler(this);
                    Program.Shutdown("SteamGuard");
                }
                else if (logOnResp.Result == EResult.AlreadyLoggedInElsewhere)
                {
                    Steam3.Shutdown();
                    Program.steamConnectionReply = "LoggedInElsewhere";
                    Steam3.RemoveHandler(this);
                    Program.Shutdown("LoggedInElseWhere");
                }
                else if (logOnResp.Result != EResult.OK)
                {
                    Steam3.Shutdown();
                    Program.steamConnectionReply = "UnknownConnectFail " + logOnResp.Result;
                    Steam3.RemoveHandler(this);
                    Program.Shutdown("UnknownConnectFail");
                }
            }

            if (msg.IsType<SteamUser.LoginKeyCallback>())
            {
                Console.WriteLine("Login key received - Setting online");
                Steam3.SteamFriends.SetPersonaState(EPersonaState.Online);
            }

            if (msg.IsType<SteamFriends.FriendAddedCallback>())
            {
                var friendAdded = (SteamFriends.FriendAddedCallback)msg;

                if (friendAdded.Result != EResult.OK)
                {
                    Program.Shutdown("friend added error");
                }
            }
            try
            {
                msg.Handle<SteamClient.DisconnectCallback>((callback) =>
                {
                    Program.Shutdown("disconnect callback");

                    return;
                });
            }
            catch { }
        }
Beispiel #31
0
 public void HandleCallback(CallbackMsg msg)
 {
     if (msg.IsType<SteamUser.LoginKeyCallback>())
         HandleLogin((SteamUser.LoginKeyCallback)msg);
     if (msg.IsType<SteamUser.LoggedOffCallback>())
         HandleLogoff((SteamUser.LoggedOffCallback)msg);
     if (msg.IsType<SteamFriends.ChatEnterCallback>())
         HandleChatEnter((SteamFriends.ChatEnterCallback)msg);
     if (msg.IsType<SteamFriends.ChatMsgCallback>())
         HandleChatMessage((SteamFriends.ChatMsgCallback)msg);
     if (msg.IsType<SteamFriends.PersonaStateCallback>())
         HandlePersonaStateChange((SteamFriends.PersonaStateCallback)msg);
     if (msg.IsType<SteamFriends.ChatMemberInfoCallback>())
         HandleChatMemberInfoCallback((SteamFriends.ChatMemberInfoCallback)msg);
     if (msg.IsType<SteamFriends.ChatActionResultCallback>())
         HandleChatActionResultCallback((SteamFriends.ChatActionResultCallback)msg);
 }
Beispiel #32
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)
                {
                    SteamUser.LogOn (new SteamUser.LogOnDetails
                         {
                        Username = Username,
                        Password = Password,
                        AuthCode = AuthCode
                    });
                }
                else
                {
                    log.Error ("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)
                {
                    log.Error ("Login Error: " + callback.Result);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface ("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    AuthCode = Console.ReadLine();
                }
            });

            msg.Handle<SteamUser.LoginKeyCallback> (callback =>
            {
                while (true)
                {
                    bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token);
                    if (authd)
                    {
                        log.Success ("User Authenticated!");
                        break;
                    }
                    else
                    {
                        log.Warn ("Authentication failed, retrying in 2s...");
                        Thread.Sleep (2000);
                    }
                }

                log.Info ("Downloading Schema...");

                Trade.CurrentSchema = Schema.FetchSchema (apiKey);

                log.Success ("Schema Downloaded!");

                SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
                SteamFriends.SetPersonaState (EPersonaState.Online);

                log.Success ("Steam Bot Logged In Completely!");

                IsLoggedIn = true;
            });
            #endregion

            #region Friends
            msg.Handle<SteamFriends.FriendsListCallback> (callback =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (!friends.Contains(friend.SteamID))
                    {
                        friends.Add(friend.SteamID);
                        if (friend.Relationship == EFriendRelationship.PendingInvitee &&
                            GetUserHandler(friend.SteamID).OnFriendAdd())
                        {
                            SteamFriends.AddFriend (friend.SteamID);
                        }
                    }
                }
            });

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

                log.Info (String.Format ("Chat Message from {0}: {1}",
                                         SteamFriends.GetFriendPersonaName (callback.Sender),
                                         callback.Message
                                         ));
                if (callback.EntryType == EChatEntryType.ChatMsg ||
                    callback.EntryType == EChatEntryType.Emote)
                {
                    GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
                }
            });
            #endregion

            #region Trading
            msg.Handle<SteamTrading.SessionStartCallback> (callback =>
            {
                OpenTrade (callback.OtherClient);
            });

            msg.Handle<SteamTrading.TradeProposedCallback> (callback =>
            {
                if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ())
                    SteamTrade.RespondToTrade (callback.TradeID, true);
                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.VacBannedInitiator ||
                    callback.Response == EEconTradeResponse.VacBannedTarget ||
                    callback.Response == EEconTradeResponse.NotLoggedIn) // uh...
                {
                    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!");
                SteamClient.Connect ();
            });
            #endregion
        }
Beispiel #33
0
 public void HandleCallback(CallbackMsg msg)
 {
     if(msg.IsType<SteamFriends.PersonaStateCallback>())
     {
         SteamFriends.PersonaStateCallback callback = (SteamFriends.PersonaStateCallback)msg;
         LoadFriendsList();
     }
 }
Beispiel #34
0
        void HandleSteamMessage (CallbackMsg msg)
        {
            #region Login
            msg.Handle<SteamClient.ConnectedCallback> (callback =>
            {
                PrintConsole ("Connection Callback: " + callback.Result, ConsoleColor.Magenta);

                if (callback.Result == EResult.OK)
                {
                    SteamUser.LogOn (new SteamUser.LogOnDetails
                         {
                        Username = Username,
                        Password = Password,
                        AuthCode = AuthCode
                    });
                }
                else
                {
                    PrintConsole ("Failed to Connect to the steam community!\n", ConsoleColor.Red);
                    SteamClient.Connect ();
                }

            });

            msg.Handle<SteamUser.LoggedOnCallback> (callback =>
            {
                PrintConsole ("Logged on callback: " + callback.Result, ConsoleColor.Magenta);

                if (callback.Result != EResult.OK)
                {
                    PrintConsole("Login Failure: " + callback.Result, ConsoleColor.Red);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    PrintConsole("This account is protected by Steam Guard. Enter the authentication code sent to the associated email address", ConsoleColor.DarkYellow);
                    AuthCode = Console.ReadLine();
                }
            });

            msg.Handle<SteamUser.LoginKeyCallback> (callback =>
            {
                while (true)
                {
                    if (Authenticate (callback))
                    {
                        PrintConsole ("Authenticated.");
                        break;
                    }
                    else
                    {
                        PrintConsole ("Retrying auth...", ConsoleColor.Red);
                        Thread.Sleep (2000);
                    }
                }

                PrintConsole ("Downloading schema...", ConsoleColor.Magenta);

                Trade.CurrentSchema = Schema.FetchSchema (apiKey);

                PrintConsole ("All Done!", ConsoleColor.Magenta);

                SteamFriends.SetPersonaName ("[SteamBot] "+DisplayName);
                SteamFriends.SetPersonaState (EPersonaState.LookingToTrade);

                PrintConsole ("Successfully Logged In!\nWelcome " + SteamUser.SteamID + "\n\n", ConsoleColor.Magenta);

                IsLoggedIn = true;
            });
            #endregion

            #region Friends
            msg.Handle<SteamFriends.PersonaStateCallback> (callback =>
            {
                SteamFriends.AddFriend (callback.FriendID);
            });

            msg.Handle<SteamFriends.FriendMsgCallback> (callback =>
            {
                //Type (emote or chat)
                EChatEntryType type = callback.EntryType;

                if (type == EChatEntryType.ChatMsg)
                {
                    PrintConsole ("[Chat] " + SteamFriends.GetFriendPersonaName (callback.Sender) + ": " + callback.Message, ConsoleColor.Magenta);

                    //string message = callback.Message;

                    string response = ChatResponse;
                    SteamFriends.SendChatMessage (callback.Sender, EChatEntryType.ChatMsg, response);
                }

            });
            #endregion

            #region Trading
            msg.Handle<SteamTrading.TradeStartSessionCallback> (call =>
            {
                CurrentTrade = new Trade (SteamUser.SteamID, call.Other, sessionId, token, apiKey, TradeListener);
            });

            msg.Handle<SteamTrading.TradeProposedCallback> (thing =>
            {
                SteamTrade.RequestTrade (thing.Other);
            });

            msg.Handle<SteamTrading.TradeRequestCallback> (thing =>
            {
                PrintConsole ("Trade Status: " + thing.Status, ConsoleColor.Magenta);

                if (thing.Status == ETradeStatus.Accepted)
                {
                    PrintConsole ("Trade accepted!", ConsoleColor.Magenta);
                }
            });
            #endregion

            #region Disconnect
            msg.Handle<SteamUser.LoggedOffCallback> (callback =>
            {
                PrintConsole ("[SteamRE] Logged Off: " + callback.Result, ConsoleColor.Magenta);
            });

            msg.Handle<SteamClient.DisconnectedCallback> (callback =>
            {
                IsLoggedIn = false;
                if (CurrentTrade != null)
                {
                    CurrentTrade = null;
                }
                PrintConsole ("[SteamRE] Disconnected from Steam Network!", ConsoleColor.Magenta);
                SteamClient.Connect ();
            });
            #endregion
        }
Beispiel #35
0
        void HandleGCMessage(CallbackMsg msg)
        {
            var details = msg as SteamGameCoordinator.MessageCallback;

            var emsg = GetEMsgDisplayString(details.EMsg);

            var messageMap = new Dictionary<uint, Action<IPacketGCMsg>>
            {
                { EGCMsg.ClientWelcome, OnGCClientWelcome },
                // SO messages
                { EGCMsg.SOCacheSubscriptionCheck, OnGCSOCacheSubscriptionCheck },
                { EGCMsg.SOCacheSubscribed, OnGCSOCacheSubscribed },
                { EGCMsg.SOCreate, OnGCSOCreate },
                { EGCMsg.SODestroy, OnGCSODestroy },
                //{ EGCMsg.SOUpdate, OnGCSOUpdate },
                { EGCMsg.UpdateItemSchema, OnGCUpdateItemSchema },
                { EGCMsg.CraftResponse, OnGCCraftResponse },
            };

            Action<IPacketGCMsg> func;
            if (!messageMap.TryGetValue(details.EMsg, out func))
            {
                Logger.WriteLine("Unhandled GC message: " + emsg);
                return;
            }

            func(details.Message);
        }
Beispiel #36
0
        void HandleSteamMessage(CallbackMsg msg, Interface gui)
        {
            //log.Debug(msg.ToString());

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

                if (callback.Result == EResult.OK)
                {
                    UserLogOn();
                }
                else
                {
                    gui.UpdateLog("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)
                {
                    gui.UpdateLog("\r\nLogin Error: " + callback.Result);
                    //log.Error("Login Error: " + callback.Result);
                    gui.Invoke((Action)(() => gui.text_username.Enabled = true));
                    gui.Invoke((Action)(() => gui.text_password.Enabled = true));
                    gui.Invoke((Action)(() => gui.button_login.Text = "Login"));
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    ////log.Interface("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    gui.Invoke((Action)(() => gui.SteamGuard()));

                    while (Application.OpenForms.Count > 1)
                    {

                    }

                    logOnDetails.AuthCode = SteamGuard.authCode;
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    gui.Invoke((Action)(() => gui.SteamGuard(true)));

                    while (Application.OpenForms.Count > 1)
                    {

                    }

                    logOnDetails.AuthCode = SteamGuard.authCode;
                }
            });

            msg.Handle<SteamUser.LoginKeyCallback>(callback =>
            {
                while (true)
                {
                    bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token);
                    if (authd)
                    {
                        gui.UpdateLog("\r\nUser authenticated!");
                        break;
                    }
                    else
                    {
                        gui.UpdateLog("\r\nAuthentication failed, retrying in 2s...");
                        Thread.Sleep(2000);
                    }
                }

                SteamFriends.SetPersonaState(EPersonaState.Snooze);

                gui.UpdateLog("\r\nLogged in completely!\r\n");
                gui.Invoke((Action)(() => gui.button_login.Text = "Logged in"));

                IsLoggedIn = true;

                while (true)
                {
                    Console.ReadLine();
                }
            });

            // 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 =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (!friends.Contains(friend.SteamID))
                    {
                        friends.Add(friend.SteamID);
                        if (friend.Relationship == EFriendRelationship.PendingInvitee &&
                            GetUserHandler(friend.SteamID).OnFriendAdd())
                        {
                            SteamFriends.AddFriend(friend.SteamID);
                        }
                    }
                }
            });*/

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

                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);
                }
            });
            #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
                {
                    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())
                    SteamTrade.RespondToTrade(callback.TradeID, true);
                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.VacBannedInitiator ||
                    callback.Response == EEconTradeResponse.VacBannedTarget ||
                    callback.Response == EEconTradeResponse.NotLoggedIn) // uh...
                {
                    CloseTrade();
                }

            });
            #endregion

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

            msg.Handle<SteamClient.DisconnectedCallback>(callback =>
            {
                IsLoggedIn = false;
                CloseTrade();
                gui.UpdateLog("\r\nDisconnected from Steam Network! Trying to reconnect...");
                //log.Warn("Disconnected from Steam Network!");
                SteamClient.Connect();
            });
            #endregion
        }
Beispiel #37
0
		void HandleSteamMessage(CallbackMsg msg) {
			#region Login
			msg.Handle<SteamClient.ConnectedCallback>(callback => {
				Util.printConsole("Connection Status " + callback.Result, this, ConsoleColor.Magenta);

				if (callback.Result == EResult.OK) {
					SteamUser.LogOn(new SteamUser.LogOnDetails {
						Username = Username,
						Password = Password
					});
				} else {
					Util.printConsole("Failed to Connect to the steam community", this, ConsoleColor.Red);
					SteamClient.Connect();
				}

			});

			msg.Handle<SteamUser.LoggedOnCallback>(callback => {
				if (callback.Result != EResult.OK) {
					Util.printConsole("Login Failure: " + callback.Result, this, ConsoleColor.Red);
				}
			});

			msg.Handle<SteamUser.LoginKeyCallback>(callback => {
				while (true) {
					if (Authenticate(callback)) {
						Util.printConsole("Authenticated.", this, ConsoleColor.Magenta);
						break;
					} else {
						Util.printConsole("Retrying auth...", this, ConsoleColor.Red);
						Thread.Sleep(2000);
					}
				}

				SteamFriends.SetPersonaName(DisplayName);
				SteamFriends.SetPersonaState(EPersonaState.LookingToTrade);

				foreach (SteamID bot in Program.bots) {
					if (SteamFriends.GetFriendRelationship(bot) != EFriendRelationship.Friend) {
						SteamFriends.AddFriend(bot);
					}
				}
				Program.bots.Add(SteamClient.SteamID);

				IsLoggedIn = true;
				queueHandler.canTrade = true;
			});
			#endregion

			#region Friends
			msg.Handle<SteamFriends.PersonaStateCallback>(callback => {
				if (callback.FriendID == SteamUser.SteamID)
					return;

				EFriendRelationship relationship = SteamFriends.GetFriendRelationship(callback.FriendID);
				if (relationship == EFriendRelationship.Friend) {
					queueHandler.acceptedRequest(callback.FriendID);
				} else if (relationship == EFriendRelationship.PendingInvitee) {
					Util.printConsole("Friend Request Pending: " + callback.FriendID + "(" + SteamFriends.GetFriendPersonaName(callback.FriendID) + ")", this, ConsoleColor.DarkCyan, true);
					if (Program.bots.Contains(callback.FriendID) || Admins.Contains(callback.FriendID)) {
						SteamFriends.AddFriend(callback.FriendID);
					}
					//steamFriends.AddFriend(callback.FriendID);
				}
			});

			msg.Handle<SteamFriends.FriendMsgCallback>(callback => {
				//Type (emote or chat)
				EChatEntryType type = callback.EntryType;

				if (type == EChatEntryType.ChatMsg) {
					string response = "";
					if (responses.ContainsKey(callback.Message.ToLower())) {
						response = responses[callback.Message.ToLower()];
					} else {
						string[] args2 = callback.Message.Split(' ');
						string text = Util.removeArg0(callback.Message);
						string[] pArgs = text.Split(' ');

						response = Extensions.getCommand(args2[0].ToLower()).call(callback.Sender, pArgs, text, this);
					}
					SteamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, response);
				}

			});
			#endregion

			#region Trading
			msg.Handle<SteamTrading.SessionStartCallback>(call => {
				Trade.TradeListener listener = TradeListener;
				if (Admins.Contains(call.OtherClient)) {
					listener = TradeListenerAdmin;
				} else if (Program.bots.Contains(call.OtherClient)) {
					listener = TradeListenerInternal;
				}
				try {
					CurrentTrade = new Trade(SteamUser.SteamID, call.OtherClient, sessionId, token, apiKey, listener);
				} catch (Exception e) {
					Util.printConsole(e.Message, this, ConsoleColor.White, true);
					CurrentTrade = null;
					Thread.Sleep(5000);
					SteamTrade.Trade(call.OtherClient);
				}
			});

			msg.Handle<SteamTrading.TradeProposedCallback>(thing => {
				Util.printConsole("Trade Proposed Callback. Other: " + thing.OtherClient, this, ConsoleColor.White, true);
				if (Program.bots.Contains(thing.OtherClient) && queueHandler.needItemsBool) {
					SteamTrade.RespondToTrade(thing.TradeID, true);
				} else {
					SteamTrade.RespondToTrade(thing.TradeID, false);
					SteamFriends.SendChatMessage(thing.OtherClient, EChatEntryType.ChatMsg, "Please wait your turn, thanks :)");
				}
			});

			msg.Handle<SteamTrading.TradeResultCallback>(thing => {
				Util.printConsole("Trade Status: " + thing.Response, this, ConsoleColor.Magenta, true);

				if (thing.Response == EEconTradeResponse.Accepted) {
					if (!Program.bots.Contains(thing.OtherClient)) {
						Util.printConsole("Trade accepted!", this, ConsoleColor.Yellow);
					}
				} else if (thing.Response == EEconTradeResponse.TargetAlreadyTrading) {
					Util.printConsole("User is already trading!", this, ConsoleColor.Magenta);
					SteamFriends.SendChatMessage(thing.OtherClient, EChatEntryType.ChatMsg, "You're at the top of the trade queue, but are in trade. We don't have all day :c");
					Thread.Sleep(10000);
					queueHandler.ignoredTrade(thing.OtherClient);
				} else if (thing.Response == EEconTradeResponse.Declined) {
					Util.printConsole("User declined trade???", this, ConsoleColor.Magenta);
					Thread.Sleep(5000);
					queueHandler.ignoredTrade(thing.OtherClient);
				} else {
					Util.printConsole("Assume User Ignored Trade Request...", this, ConsoleColor.Magenta);
					queueHandler.ignoredTrade(thing.OtherClient);
				}
			});
			#endregion

			#region Disconnect
			msg.Handle<SteamUser.LoggedOffCallback>(callback => {
				Util.printConsole("Told to log off by server (" + callback.Result + "), attemping to reconnect", this, ConsoleColor.Magenta);
				SteamClient.Connect();
			});

			msg.Handle<SteamClient.DisconnectedCallback>(callback => {
				IsLoggedIn = false;
				if (CurrentTrade != null) {
					CurrentTrade = null;
				}
				Util.printConsole("Disconnected from Steam Network, attemping to reconnect", this, ConsoleColor.Magenta);
				SteamClient.Connect();
			});
			#endregion
		}
Beispiel #38
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;
            }
        }