Beispiel #1
0
        public override void HandlePacket(ref NetworkPacket Packet, ref SteamClient Client)
        {
            redBuffer Buffer = new redBuffer();

            // We send the length first.
            Client.UpdateFriendslist();
            Buffer.WriteUInt32((UInt32)Client.FriendsList.Count);

            foreach(SteamFriend Friend in Client.FriendsList)
            {
                Buffer.WriteUInt32((UInt32)Friend.Status);
                Buffer.WriteBlob(Friend.Username);
                Buffer.WriteUInt64(Friend.XUID);
            }

            Packet.CreatePacket(Packet._TransactionID, 200, Buffer, Client);

            // Clear the buffer.
            Buffer = new redBuffer();

            // Serialize the packet.
            Packet.Serialize(ref Buffer, Client);

            // Send the response.
            SteamServer.Send(Client.ClientID, Buffer.GetBuffer());
        }
        public GameCoordinator(uint appID, SteamClient steamClient, CallbackManager callbackManager)
        {
            // Map gc messages to our callback functions
            GCMessageMap = new Dictionary<uint, Action<IPacketGCMsg>>
            {
                { (uint)EGCBaseClientMsg.k_EMsgGCClientWelcome, OnClientWelcome },
                { (uint)EGCItemMsg.k_EMsgGCUpdateItemSchema, OnItemSchemaUpdate },
                { (uint)EGCBaseMsg.k_EMsgGCSystemMessage, OnSystemMessage },
                { (uint)EGCBaseClientMsg.k_EMsgGCClientConnectionStatus, OnClientConnectionStatus },
                { (uint)4008 /* TF2's k_EMsgGCClientGoodbye */, OnClientConnectionStatus }
            };

            this.AppID = appID;
            this.SteamClient = steamClient;
            this.SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
            this.Name = string.Format("GC {0}", appID);

            // Make sure Steam knows we're playing the game
            Timer = new System.Timers.Timer();
            Timer.Elapsed += OnTimerPlayGame;
            Timer.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds;
            Timer.Start();

            Timer = new System.Timers.Timer();
            Timer.Elapsed += OnTimer;

            callbackManager.Register(new Callback<SteamGameCoordinator.MessageCallback>(OnGameCoordinatorMessage));
        }
        public void OnConnected(SteamClient.ConnectedCallback callback)
        {
            if (callback.Result != EResult.OK)
            {
                this.SetText("Error connecting to Steam: " + callback.Result);
                isRunning = false;
            }
            else
            {

                this.SetText("Connected to Steam Network.");
                if (SteamAuthCode.Text != "")
                {
                    user.LogOn(new SteamUser.LogOnDetails
                    {
                        Username = SteamUserName.Text,
                        Password = SteamPassword.Text,
                        AuthCode = SteamAuthCode.Text
                    });
                }
                else
                {
                    user.LogOn(new SteamUser.LogOnDetails
                    {
                        Username = SteamUserName.Text,
                        Password = SteamPassword.Text
                    });
                }
            }
        }
        public Steam()
        {
            Client = new SteamClient();

            User = Client.GetHandler<SteamUser>();
            Apps = Client.GetHandler<SteamApps>();
            Friends = Client.GetHandler<SteamFriends>();
            UserStats = Client.GetHandler<SteamUserStats>();

            CallbackManager = new CallbackManager(Client);

            Client.AddHandler(new ReadMachineAuth());

            new Connection(CallbackManager);
            new PICSProductInfo(CallbackManager);
            new PICSTokens(CallbackManager);
            new LicenseList(CallbackManager);
            new WebAuth(CallbackManager);
            new FreeLicense(CallbackManager);

            if (!Settings.IsFullRun)
            {
                new AccountInfo(CallbackManager);
                new ClanState(CallbackManager);
                new ChatMemberInfo(CallbackManager);
                new GameCoordinator(Client, CallbackManager);

                new Watchdog();
            }

            PICSChanges = new PICSChanges(CallbackManager);
            DepotProcessor = new DepotProcessor(Client, CallbackManager);

            IsRunning = true;
        }
Beispiel #5
0
        public bool Invoke()
        {
            return Task.Run( async () => {

                try {

                    SteamID targetUser = new SteamID( "76561198129947779" );

                    SteamClient client = new SteamClient();
                    client.Authenticator = UserAuthenticator.ForProtectedResource( AccessConstants.OAuthAccessToken );

                    chatClient.SteamChatConnectionChanged += chatClient_SteamChatConnected;

                    chatClient.SteamChatMessagesReceived += chatClient_SteamChatMessagesReceived;
                    chatClient.SteamChatUserStateChange += chatClient_SteamChatUserStateChange;

                    chatClient.LogOn( client ).Wait();

                    while( true ) {
                        switch( WriteConsole.Prompt( "Command (msg, status): " ) ) {
                            case "msg": await chatClient.SendMessage( targetUser, WriteConsole.Prompt( "Type New Message: " ) ); break;
                            case "dcn": await chatClient.Disconnect(); break;
                        }
                    }

                } catch( Exception e ) {
                    WriteConsole.Error( e.Message + "\n" + e.ToString() );
                    return false;
                }

            } ).Result;
        }
        public GameCoordinator(SteamClient steamClient, CallbackManager manager)
        {
            SessionMap = new Dictionary<uint, SessionInfo>();

            // Map gc messages to our callback functions
            MessageMap = new Dictionary<uint, Action<uint, IPacketGCMsg>>
            {
                { (uint)EGCBaseClientMsg.k_EMsgGCClientConnectionStatus, OnConnectionStatus },
                { (uint)EGCBaseClientMsg.k_EMsgGCClientWelcome, OnWelcome },
                { (uint)EGCItemMsg.k_EMsgGCUpdateItemSchema, OnItemSchemaUpdate },
                { (uint)EGCItemMsg.k_EMsgGCClientVersionUpdated, OnVersionUpdate },
                { (uint)EGCBaseMsg.k_EMsgGCSystemMessage, OnSystemMessage },

                // TF2 specific messages
                { k_EMsgGCClientGoodbye, OnConnectionStatus },
                { (uint)EGCItemMsg.k_EMsgGCGoldenWrenchBroadcast, OnWrenchBroadcast },
                { k_EMsgGCTFSpecificItemBroadcast, OnItemBroadcast },
            };

            SteamGameCoordinator = steamClient.GetHandler<SteamGameCoordinator>();

            SessionTimer = new Timer();
            SessionTimer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds;
            SessionTimer.Elapsed += OnSessionTick;
            SessionTimer.Start();

            manager.Subscribe<SteamGameCoordinator.MessageCallback>(OnGameCoordinatorMessage);
            manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
            manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
        }
        private void OnConnected(SteamClient.ConnectedCallback callback)
        {
            if (callback.Result != EResult.OK)
            {
                _checkResult = ECheckResult.ConnectFailed;
                _isRunning = false;
                return;
            }

            byte[] sentryHash = null;
            if (File.Exists(_sentryLoc))
            {
                byte[] sentryFile = File.ReadAllBytes(_sentryLoc);
                sentryHash = CryptoHelper.SHAHash(sentryFile);
            }
            else if (_operation == EOperationType.CheckSentry || _operation == EOperationType.AddToSentry)
            {
                _checkResult = ECheckResult.SentryMissing;
                _isRunning = false;
                return;
            }

            _steamUser.LogOn(new SteamUser.LogOnDetails
            {
                Username = _username,
                Password = _password,
                AuthCode = _authCode,
                TwoFactorCode = _twoFactorAuth,
                SentryFileHash = sentryHash,
            });
        }
Beispiel #8
0
        private static void Login()
        {
            steamClient = new SteamClient();
            callBackManager = new CallbackManager(steamClient);
            steamFriends = steamClient.GetHandler<SteamFriends>();
            steamUser = steamClient.GetHandler<SteamUser>();

            callBackManager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
            callBackManager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedIn);
            callBackManager.Subscribe<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
            callBackManager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
            callBackManager.Subscribe<SteamFriends.FriendMsgCallback>(OnMsgRecieved);
            callBackManager.Subscribe<SteamUser.AccountInfoCallback>(OnAccountInfo);
            callBackManager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
            callBackManager.Subscribe<SteamFriends.FriendAddedCallback>(OnFriendAdded);
            callBackManager.Subscribe<SteamFriends.PersonaStateCallback>(OnFriendPersonaChange);

            SteamDirectory.Initialize().Wait();
            steamClient.Connect();

            isRunning = true;

            while (isRunning)
            {
                callBackManager.RunWaitCallbacks(TimeSpan.FromSeconds(0.5));
            }

            Console.ReadKey();
        }
Beispiel #9
0
        public void GET_GetOwnedGames_ByClass()
        {
            SteamClient client = new SteamClient();
            client.Authenticator = SteamSharp.Authenticators.APIKeyAuthenticator.ForProtectedResource( AccessConstants.APIKey );

            var response = PlayerService.GetOwnedGames( client, "76561197960434622", true, true );

            Assert.IsNotNull( response );
            Assert.IsInstanceOfType( response, typeof(PlayerService.OwnedGames) );

            Assert.IsNotNull( response.GameCount );
            Assert.IsTrue( ( response.GameCount > 5 ) );

            Assert.IsNotNull( response.Games );
            Assert.IsTrue( ( response.Games.Count > 0 ) );

            Assert.IsNotNull( response.Games[1] );

            Assert.IsNotNull( response.Games[1].GameID );
            Assert.IsNotNull( response.Games[1].HasCommunityVisibileStats );
            Assert.IsNotNull( response.Games[1].ImgIconURL );
            Assert.IsNotNull( response.Games[1].ImgLogoURL );
            Assert.IsNotNull( response.Games[1].Name );
            Assert.IsNotNull( response.Games[1].PlaytimeForever );
            Assert.IsNotNull( response.Games[1].PlaytimeTwoWeeks );
        }
Beispiel #10
0
        public void GET_GetRecentlyPlayedGames_ByClass()
        {
            SteamClient client = new SteamClient();
            client.Authenticator = SteamSharp.Authenticators.APIKeyAuthenticator.ForProtectedResource( AccessConstants.APIKey );

            var response = PlayerService.GetRecentlyPlayedGames( client, "76561197960434622" );

            Assert.IsNotNull( response );
            Assert.IsInstanceOfType( response, typeof( PlayerService.PlayedGames ) );

            Assert.IsNotNull( response.TotalCount );

            Assert.IsNotNull( response.Games );

            // Note: This test case will absolutely blow up if Robin goes two weeks without playing a game :)
            Assert.IsTrue( ( response.Games.Count > 0 ) );

            Assert.IsNotNull( response.Games[0] );

            Assert.IsNotNull( response.Games[0].GameID );
            Assert.IsNotNull( response.Games[0].ImgIconURL );
            Assert.IsNotNull( response.Games[0].ImgLogoURL );
            Assert.IsNotNull( response.Games[0].Name );
            Assert.IsNotNull( response.Games[0].PlaytimeForever );
            Assert.IsNotNull( response.Games[0].PlaytimeTwoWeeks );
        }
        public virtual void OnConnect(SteamClient.ConnectedCallback e)
        {
            if (e.Result != EResult.OK)
            {
                VersatileIO.Error("Unable to connect to Steam: " + e.Result.ToString());

                Stop();
                return;
            }

            VersatileIO.Success("Connected to Steam!");
            VersatileIO.Debug("Logging in user '{0}'...", LoginUsername);

            byte[] hash = null;
            if (!File.Exists(SentryFilePath))
            {
                byte[] sentryFile = File.ReadAllBytes(SentryFilePath);
                hash = CryptoHelper.SHAHash(sentryFile);
            }

            SteamUser.LogOnDetails logon = new SteamUser.LogOnDetails();
            logon.Username = LoginUsername;
            logon.Password = password;
            logon.AuthCode = steamGuardCode;
            logon.TwoFactorCode = twoFactorAuth;
            logon.SentryFileHash = hash;

            User.LogOn(logon);
        }
        public bool Invoke()
        {
            try {

                SteamUser user = Login();
                if( user == null )
                    return false;

                WriteConsole.Information( "Now attempting basic protected API call..." );

                SteamClient client = new SteamClient();
                client.Authenticator = UserAuthenticator.ForProtectedResource( user );

                // Validate basic protected API call
                var response = SteamCommunity.GetFriendsList( client, user.SteamID );
                if( response.Friends == null )
                    throw new Exception( "Unable to get protected data!" );

                WriteConsole.Success( "Protected data retrieved!" );

                return true;

            } catch( Exception e ) {
                WriteConsole.Error( e.Message + "\n" + e.ToString() );
                return false;
            }
        }
Beispiel #13
0
        public void GET_Add_QueryString_Params()
        {
            using( SimulatedServer.Create( AccessConstants.SimulatedServerUrl, QueryString_Echo ) ) {

                // All Params added, GetOrPost & QueryString, should be present in the result set
                SteamClient client = new SteamClient( AccessConstants.SimulatedServerUrl );
                var request = new SteamRequest( "/resource" );

                request.AddParameter( "param1", "1234", ParameterType.GetOrPost );
                request.AddParameter( "param2", "5678", ParameterType.QueryString );

                var response = client.Execute( request );

                Assert.IsNotNull( response.Content );

                string[] temp = response.Content.Split( '|' );

                NameValueCollection coll = new NameValueCollection();
                foreach( string s in temp ) {
                    var split = s.Split( '=' );
                    coll.Add( split[0], split[1] );
                }

                Assert.IsNotNull( coll["param1"] );
                Assert.AreEqual( "1234", coll["param1"] );

                Assert.IsNotNull( coll["param2"] );
                Assert.AreEqual( "5678", coll["param2"] );

            }
        }
Beispiel #14
0
		public Bot(Configuration.BotInfo config, string apiKey, bool debug = false) {
			sql = new Sql();

			Username = config.Username;
			Password = config.Password;
			DisplayName = config.DisplayName;
			Admins = config.Admins;
			id = config.Id;
			this.apiKey = apiKey;

			TradeListener = new ScrapTrade(this);
			TradeListenerInternal = new ExchangeTrade(this);
			TradeListenerAdmin = new AdminTrade(this);

			List<object[]> result = sql.query("SELECT text, response FROM responses");
			foreach (object[] row in result) {
				responses.Add(((string) row[0]).ToLower(), (string) row[1]);
			}

			// Hacking around https
			ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

			SteamClient = new SteamClient();
			SteamTrade = SteamClient.GetHandler<SteamTrading>();
			SteamUser = SteamClient.GetHandler<SteamUser>();
			SteamFriends = SteamClient.GetHandler<SteamFriends>();
			queueHandler = new QueueHandler(this);

			SteamClient.Connect();

			while (true) {
				Update();
			}
		}
Beispiel #15
0
		public void GetNextJobIDSetsProcessIDToZero()
		{
			var steamClient = new SteamClient();
			var jobID = steamClient.GetNextJobID();

			Assert.Equal(0u, jobID.ProcessID);
		}
Beispiel #16
0
        public GCClient()
        {
            SteamClient = new SteamClient();
            SteamClient.AddHandler( new SteamGames() );

            CallbackManager = new CallbackManager( SteamClient );

            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
            SteamApps = SteamClient.GetHandler<SteamApps>();
            SteamGames = SteamClient.GetHandler<SteamGames>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();

            new Callback<SteamClient.ConnectedCallback>( OnConnected, CallbackManager );
            new Callback<SteamClient.DisconnectedCallback>( OnDisconnected, CallbackManager );

            new Callback<SteamUser.LoggedOnCallback>( OnLoggedOn, CallbackManager );
            new Callback<SteamUser.LoggedOffCallback>( OnLoggedOff, CallbackManager );

            new Callback<SteamApps.LicenseListCallback>( OnLicenseList, CallbackManager );

            new Callback<SteamGameCoordinator.MessageCallback>( OnGCMessage, CallbackManager );

            new JobCallback<SteamApps.AppOwnershipTicketCallback>( OnAppTicket, CallbackManager );
        }
Beispiel #17
0
        public SteamBot(string newUser, string newPass)
        {
            // Bot user and password
            user = newUser;
            pass = newPass;

            // create our steamclient instance
            steamClient = new SteamClient( System.Net.Sockets.ProtocolType.Tcp );
            // create the callback manager which will route callbacks to function calls
            manager = new CallbackManager( steamClient );

            // get the steamuser handler, which is used for logging on after successfully connecting
            steamUser = steamClient.GetHandler<SteamUser>();
            // get the steam friends handler, which is used for interacting with friends on the network after logging on
            steamFriends = steamClient.GetHandler<SteamFriends>();

            // register a few callbacks we're interested in
            // these are registered upon creation to a callback manager, which will then route the callbacks
            // to the functions specified
            new Callback<SteamClient.ConnectedCallback>( OnConnected, manager );
            new Callback<SteamClient.DisconnectedCallback>( OnDisconnected, manager );

            new Callback<SteamUser.LoggedOnCallback>( OnLoggedOn, manager );

            // we use the following callbacks for friends related activities
            new Callback<SteamUser.AccountInfoCallback>( OnAccountInfo, manager );
            new Callback<SteamFriends.FriendsListCallback>( OnFriendsList, manager );
            new Callback<SteamFriends.FriendMsgCallback> (OnFriendMessage, manager);

            // initiate the connection
            steamClient.Connect();

            // Make sure the main loop runs
            isRunning = true;
        }
        private void OnConnected(SteamClient.ConnectedCallback callback)
        {
            if (callback.Result != EResult.OK)
            {
                GameCoordinator.UpdateStatus(0, callback.Result.ToString());

                IRC.Instance.SendEmoteAnnounce("failed to connect: {0}", callback.Result);

                Log.WriteInfo("Steam", "Could not connect: {0}", callback.Result);

                return;
            }

            GameCoordinator.UpdateStatus(0, EResult.NotLoggedOn.ToString());

            Log.WriteInfo("Steam", "Connected, logging in to cellid {0}...", LocalConfig.CellID);

            byte[] sentryHash = null;

            if (LocalConfig.Sentry != null)
            {
                sentryHash = CryptoHelper.SHAHash(LocalConfig.Sentry);
            }

            Steam.Instance.User.LogOn(new SteamUser.LogOnDetails
            {
                Username = Settings.Current.Steam.Username,
                Password = Settings.Current.Steam.Password,
                CellID = LocalConfig.CellID,
                AuthCode = AuthCode,
                SentryFileHash = sentryHash
            });
        }
Beispiel #19
0
        static void LogIn()
        {
            steamClient = new SteamClient();
            callbackManager = new CallbackManager(steamClient);
            steamUser = steamClient.GetHandler<SteamUser>();
            steamFriends = steamClient.GetHandler<SteamFriends>();
            steamTrading = steamClient.GetHandler<SteamTrading>();
            new Callback<SteamClient.ConnectedCallback>(OnConnect,callbackManager);
            new Callback<SteamUser.LoggedOnCallback>(OnLoggedOn, callbackManager);
            new Callback<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth, callbackManager);
            new Callback<SteamClient.DisconnectedCallback>(OnDisconnected, callbackManager);
            new Callback<SteamUser.AccountInfoCallback>(OnAccountInfo, callbackManager);
            new Callback<SteamFriends.FriendMsgCallback>(OnChatMessage, callbackManager);
            new Callback<SteamFriends.FriendsListCallback>(OnFriendInvite, callbackManager);
            new Callback<SteamTrading.TradeProposedCallback>(OnTradeOffer, callbackManager);
            new Callback<SteamTrading.SessionStartCallback>(OnTradeWindow, callbackManager);
            new Callback<SteamTrading.TradeResultCallback>(OnTradeResult, callbackManager);

            isRunning = true;

            Console.WriteLine("Attempting to connect to steam...");

            steamClient.Connect();

            while(isRunning)
            {
                callbackManager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }
            Console.ReadKey();
        }
Beispiel #20
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            Username     = config.Username;
            Password     = config.Password;
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            AuthCode     = null;
            log          = new Log (config.LogFile, this);
            CreateHandler = handlerCreator;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);
                    HandleSteamMessage (msg);
                }
            });

            new Thread(() => // Trade Polling if needed
            {
                while (true)
                {
                    Thread.Sleep (TradePollingInterval);
                    if (CurrentTrade != null)
                    {
                        try
                        {
                            CurrentTrade.Poll ();
                        }
                        catch (Exception e)
                        {
                            log.Error ("Error Polling Trade: " + e);
                        }
                    }
                }
            }).Start ();

            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }
Beispiel #21
0
        public void GET_GetPlayerSummaries_ByClass_Unauthenticated()
        {
            SteamClient client = new SteamClient();

            AssertException.Throws<SteamAuthenticationException>( () => {
                SteamCommunity.GetUsers( client, SteamID.CreateFromList( new string[] { "76561197960435530", "76561198067189899" } ) );
            } );
        }
Beispiel #22
0
        public void GET_GetRecentlyPlayedGames_ByClass_NoAuth()
        {
            SteamClient client = new SteamClient();

            AssertException.Throws<SteamAuthenticationException>( () => {
                var response = PlayerService.GetRecentlyPlayedGames( client, "76561197960434622" );
            });
        }
Beispiel #23
0
        public void GET_GetFriendList_ByClass_Unauthenticated()
        {
            SteamClient client = new SteamClient();

            AssertException.Throws<SteamAuthenticationException>( () => {
                SteamCommunity.GetFriendsList( client, new SteamID( "76561197960435530" ) );
            } );
        }
Beispiel #24
0
        public void Detect_Malformed_BaseApi()
        {
            var request = new SteamRequest( "resource" );

            var client = new SteamClient(  "Definitely isn't a URI... How sad :(" );

            AssertException.Throws<FormatException>( () => { client.BuildUri( request ); } );
        }
Beispiel #25
0
        public void AsyncJobCtorRegistersJob()
        {
            SteamClient client = new SteamClient();

            AsyncJob<Callback> asyncJob = new AsyncJob<Callback>( client, 123 );

            Assert.True( client.jobManager.asyncJobs.ContainsKey( asyncJob ), "Async job dictionary should contain the jobid key" );
            Assert.True( client.jobManager.asyncJobs.ContainsKey( 123 ), "Async job dictionary should contain jobid key as a value type" );
        }
        public void NonExistant_Base_Returns_Error()
        {
            SteamClient client = new SteamClient( "http://hopefullyth-is-domain-nev-rexists.com" );

            SteamRequest request = new SteamRequest( "/resource" );
            var response = client.Execute( request );

            Assert.AreEqual( ResponseStatus.Error, response.ResponseStatus );
        }
Beispiel #27
0
        public void GET_GetGlobalAchievementPercentagesForApp_NoValues()
        {
            SteamClient client = new SteamClient();
            SteamRequest request = new SteamRequest( "ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/" );

            var response = client.Execute( request );

            Assert.AreEqual( HttpStatusCode.BadRequest, response.StatusCode );
        }
Beispiel #28
0
        public void GET_GetGlobalAchievementPercentagesForApp_ByClass()
        {
            SteamClient client = new SteamClient();

            var response = SteamCommunity.GetGlobalAchievementPercentagesForApp( client, 440 );

            Assert.IsNotNull( response );
            Assert.IsInstanceOfType( response, typeof( List<SteamCommunity.GlobalAchievement> ) );
        }
Beispiel #29
0
        public SteamConnection(IntPtr ic)
        {
            this.ic = ic;

            client = new SteamClient();

            friends = client.GetHandler<SteamFriends>();
            user = client.GetHandler<SteamUser>();
        }
Beispiel #30
0
        public static void Connect()
        {
            Client = new SteamClient(ProtocolType.Udp);
            Friends = Client.GetHandler<SteamFriends>();
            User = Client.GetHandler<SteamUser>();
            Chat = new Chat();

            Client.Connect();
        }
Beispiel #31
0
        public void AsyncJobMultipleContinuesAsynchronously()
        {
            SteamClient client = new SteamClient();

            var asyncJob  = new AsyncJobMultiple <Callback>(client, 123, call => true);
            var asyncTask = asyncJob.ToTask();

            var continuationThreadID = -1;
            var continuation         = asyncTask.ContinueWith(t =>
            {
                continuationThreadID = Environment.CurrentManagedThreadId;
            }, TaskContinuationOptions.ExecuteSynchronously);

            var completionThreadID = Environment.CurrentManagedThreadId;

            asyncJob.AddResult(new Callback {
                JobID = 123
            });

            WaitForTaskWithoutRunningInline(continuation);

            Assert.NotEqual(-1, continuationThreadID);
            Assert.NotEqual(completionThreadID, continuationThreadID);
        }
Beispiel #32
0
        public ProtectedAccount(JsonAccounts.JsonAccount json) : base(json)
        {
            _log = LogCreator.Create("GC - " + json.Username + " (Protected)");

            _sentry = new Sentry.Sentry(this);

            _steamClient     = new SteamClient();
            _callbacks       = new CallbackManager(_steamClient);
            _steamUser       = _steamClient.GetHandler <SteamUser>();
            _steamFriends    = _steamClient.GetHandler <SteamFriends>();
            _gameCoordinator = _steamClient.GetHandler <SteamGameCoordinator>();

            // Initialize debug network sniffer when debug mode is enabled
            if (Titan.Instance.Options.Debug)
            {
                var dir = new DirectoryInfo(Path.Combine(Titan.Instance.DebugDirectory.ToString(), json.Username));
                if (!dir.Exists)
                {
                    dir.Create();
                }

                _steamClient.DebugNetworkListener = new NetHookNetworkListener(
                    dir.ToString()
                    );
            }

            if (json.SharedSecret != null)
            {
                _sgAccount = new SteamGuardAccount
                {
                    SharedSecret = json.SharedSecret
                };
            }

            _log.Debug("Successfully initialized account object for " + json.Username + ".");
        }
Beispiel #33
0
        public Steam3Session(SteamClient steamClient, CallbackManager callbackManager)
        {
            this.bConnected  = false;
            this.bConnecting = false;
            this.bAborted    = false;

            this.steamClient = steamClient;

            this.steamUser = this.steamClient.GetHandler <SteamUser>();
            this.steamApps = this.steamClient.GetHandler <SteamApps>();
            var steamUnifiedMessages = this.steamClient.GetHandler <SteamUnifiedMessages>();

            this.steamPublishedFile = steamUnifiedMessages.CreateService <IPublishedFile>();

            this.callbacks = callbackManager;

            this.callbacks.Subscribe <SteamClient.ConnectedCallback>(ConnectedCallback);
            this.callbacks.Subscribe <SteamClient.DisconnectedCallback>(DisconnectedCallback);
            this.callbacks.Subscribe <SteamUser.LoggedOnCallback>(LogOnCallback);
            this.callbacks.Subscribe <SteamUser.SessionTokenCallback>(SessionTokenCallback);
            this.callbacks.Subscribe <SteamApps.LicenseListCallback>(LicenseListCallback);
            this.callbacks.Subscribe <SteamUser.UpdateMachineAuthCallback>(UpdateMachineAuthCallback);
            this.callbacks.Subscribe <SteamUser.LoginKeyCallback>(LoginKeyCallback);
        }
Beispiel #34
0
        /*public void InstallGame(UInt64 GameID)
         * {
         *  CGameID gameID = new CGameID(GameID);
         *  switch (gameID.AppType)
         *  {
         *      // Basic Steam App
         *      case CGameID.EGameID.k_EGameIDTypeApp:
         *          {
         *              string InstallCommand = $"steam://install/{GameID}";
         *              string installPath = Steamworks.GetInstallPath();
         *              string steamEXE = Path.Combine(installPath, @"steam.exe");
         *              Process.Start(steamEXE, InstallCommand);
         *          }
         *          break;
         *      case CGameID.EGameID.k_EGameIDTypeGameMod:
         *          break;
         *      case CGameID.EGameID.k_EGameIDTypeShortcut:
         *          break;
         *  }
         * }*/

        /*public string[] GetGameLibraries()
         * {
         *  try
         *  {
         *      int CountBaseFolders = ClientAppManager.GetNumInstallBaseFolders();
         *      string[] BaseFolders = new string[CountBaseFolders];
         *      for (int x = 0; x < CountBaseFolders; x++)
         *      {
         *          StringBuilder builder = new StringBuilder(1024);
         *          ClientAppManager.GetInstallBaseFolder(x, builder);
         *          BaseFolders[x] = builder.ToString();
         *      }
         *      return BaseFolders;
         *  }
         *  catch
         *  {
         *      return new string[0];
         *  }
         * }*/

        /*public EAppUpdateError? InstallGame(UInt64 GameID, int GameLibraryIndex)
         * {
         *  CGameID gameID = new CGameID(GameID);
         *  switch (gameID.AppType)
         *  {
         *      // Basic Steam App
         *      case CGameID.EGameID.k_EGameIDTypeApp:
         *          {
         *              return ClientAppManager.InstallApp(gameID.AppID, GameLibraryIndex, false);
         *          }
         *          break;
         *      case CGameID.EGameID.k_EGameIDTypeGameMod:
         *          break;
         *      case CGameID.EGameID.k_EGameIDTypeShortcut:
         *          break;
         *  }
         *  return null;
         * }*/



        /*public void StartBigPicture()
         * {
         *  string installPath = Steamworks.GetInstallPath();
         *  string steamEXE = Path.Combine(installPath, @"steam.exe");
         *  Process.Start(steamEXE, "steam://open/bigpicture");
         * }*/

        /*public bool IsInBigPicture()
         * {
         *  return WrappedContext.BigPicturePID > 0;
         * }*/

        public void Init(string ProxyServerPath = null, bool SearchSubfolders = false)
        {
            Steam.Load();
            SteamClient = Steam.CreateInterface <ISteamClient017>();
            if (SteamClient == null)
            {
                throw new Exception();
            }
            Pipe = SteamClient.CreateSteamPipe();
            if (Pipe == 0)
            {
                throw new Exception();
            }
            User = SteamClient.ConnectToGlobalUser(Pipe);
            if (User == 0)
            {
                throw new Exception();
            }
            SteamApps = SteamClient.GetISteamApps <ISteamApps008>(User, Pipe);
            if (SteamApps == null)
            {
                throw new Exception();
            }
        }
Beispiel #35
0
    // This should only ever get called on first load and after an Assembly reload, You should never Disable the Steamworks Manager yourself.
    private void OnEnable()
    {
        if (s_instance == null)
        {
            s_instance = this;
        }

        if (!m_bInitialized)
        {
            return;
        }
        else
        {
            m_GameOverlayActivated = Callback <GameOverlayActivated_t> .Create(OnGameOverlayActivated);
        }

        if (m_SteamAPIWarningMessageHook == null)
        {
            // Set up our callback to recieve warning messages from Steam.
            // You must launch with "-debug_steamapi" in the launch args to recieve warnings.
            m_SteamAPIWarningMessageHook = new SteamAPIWarningMessageHook_t(SteamAPIDebugTextHook);
            SteamClient.SetWarningMessageHook(m_SteamAPIWarningMessageHook);
        }
    }
Beispiel #36
0
        public static bool Init()
        {
            try
            {
                if (SteamAPI.RestartAppIfNecessary(AppID))
                {
                    Environment.Exit(0);
                }
            } catch (Exception)
            {
                return(false);
            }

            Initialised = SteamAPI.Init();

            if (Initialised)
            {
                SteamClient.SetWarningMessageHook(SteamAPIDebugTextHook);
            }

            Workshop.RegisterCallbacks();

            return(Initialised);
        }
Beispiel #37
0
        public override void OnBeAdded(IMono mono)
        {
            base.OnBeAdded(mono);
            uint appId = GetAppId();

            // 使用try防止崩溃
            try
            {
                SteamClient.Init(appId);
            }
            catch (Exception e)
            {
                CLog.Info("Error starting steam client: {0}", e);
                SteamClient.Shutdown();
            }
            if (SteamClient.IsValid)
            {
                IsSDKInited = true;
            }
            else
            {
                SteamClient.Shutdown();
            }
        }
        public async Task AsyncJobMultipleContinuesAsynchronously()
        {
            SteamClient client = new SteamClient();

            var asyncJob  = new AsyncJobMultiple <Callback>(client, 123, call => true);
            var asyncTask = asyncJob.ToTask();

            var continuationThreadID = -1;
            var continuation         = asyncTask.ContinueWith(t =>
            {
                continuationThreadID = Thread.CurrentThread.ManagedThreadId;
            }, TaskContinuationOptions.ExecuteSynchronously);

            var completionThreadID = Thread.CurrentThread.ManagedThreadId;

            asyncJob.AddResult(new Callback {
                JobID = 123
            });

            await continuation;

            Assert.NotEqual(-1, continuationThreadID);
            Assert.NotEqual(completionThreadID, continuationThreadID);
        }
Beispiel #39
0
        private async void OnLoggedOn(SteamUser.LoggedOnCallback loggedOnCallback)
        {
            try
            {
                switch (loggedOnCallback.Result)
                {
                case EResult.OK:
                    CookieManager.BotSequenceNumber = SequenceNumber;
                    CookieManager.ConnectedUniverse = SteamClient.ConnectedUniverse;
                    CookieManager.SteamId           = _steamUser.SteamID;
                    CookieManager.WebApiUserNonce   = loggedOnCallback.WebAPIUserNonce;
                    _logger.Info($"#{SequenceNumber} logged on.");
                    try
                    {
                        await SteamFriends.SetPersonaName($"其乐机器人 Keylol.com #{SequenceNumber}");

                        await SteamFriends.SetPersonaState(EPersonaState.LookingToPlay);

                        _coordinator.Consume(
                            coordinator => coordinator.UpdateBot(Id, null, true, _steamUser.SteamID.Render(true)));
                        _logger.Info($"#{SequenceNumber} is now online.");
                        var playGameMessage = new ClientMsgProtobuf <CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
                        playGameMessage.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed
                        {
                            game_id = new GameID(570)     // 默认玩 Dota2
                        });
                        SteamClient.Send(playGameMessage);
                    }
                    catch (TaskCanceledException)
                    {
                        _logger.Fatal($"#{SequenceNumber} Set online failed.");
                        Restart();
                        return;
                    }
                    break;

                case EResult.AccountLogonDenied:
                    _logger.Fatal(
                        $"#{SequenceNumber} Need auth code (from email {loggedOnCallback.EmailDomain}) to login.");
                    break;

                case EResult.AccountLoginDeniedNeedTwoFactor:
                    _logger.Fatal($"#{SequenceNumber} Need two-factor auth code (from authenticator app) to login.");
                    break;

                default:
                    _logger.Fatal($"#{SequenceNumber} LoggedOnCallback invalid result: {loggedOnCallback.Result}.");
                    break;
                }
                if (_loginPending)
                {
                    LoginSemaphore.Release();
                    _loginPending = false;
                }
            }
            catch (Exception e)
            {
                _logger.Fatal($"#{SequenceNumber} Fatal unhandled exception (OnLoggedOn) : {e.Message}");
                Restart();
            }
        }
Beispiel #40
0
        private async Task Run()
        {
            try
            {
                if (File.Exists("config.json"))
                {
                    using (var sr = new StreamReader("config.json"))
                    {
                        string jsonString = string.Empty;
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            jsonString += line;
                        }
                        botConfig = JsonConvert.DeserializeObject <ConfigModel>(jsonString);
                        if (string.IsNullOrEmpty(botConfig.login))
                        {
                            Console.WriteLine("ERROR: Steam login is empty");
                            await Task.Delay(3000);

                            return;
                        }
                        if (string.IsNullOrEmpty(botConfig.password))
                        {
                            Console.WriteLine("ERROR: Steam password is empty");
                            await Task.Delay(3000);

                            return;
                        }
                        if (string.IsNullOrEmpty(botConfig.msgText))
                        {
                            Console.WriteLine("ERROR: Message content is empty");
                            await Task.Delay(3000);

                            return;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("ERROR: config.json file is not found");
                    await Task.Delay(3000);

                    return;
                }
                if (File.Exists("chat_regions.txt"))
                {
                    chatRegions = File.ReadAllLines("chat_regions.txt");
                }

                //DebugLog.AddListener(new DebugListener());
                //DebugLog.Enabled = true;
                //create our steamclient instance
                var cellid = 0u;

                // if we've previously connected and saved our cellid, load it.
                if (File.Exists("cellid.txt"))
                {
                    if (!uint.TryParse(File.ReadAllText("cellid.txt"), out cellid))
                    {
                        Console.WriteLine("Error parsing cellid from cellid.txt. Continuing with cellid 0.");
                        cellid = 0;
                    }
                    else
                    {
                        Console.WriteLine($"Using persisted cell ID {cellid}");
                    }
                }
                var configuration = SteamConfiguration.Create((config) =>
                {
                    config.WithServerListProvider(new FileStorageServerListProvider("servers_list.bin"));
                    config.WithCellID(cellid);
                });

                steamClient = new SteamClient(configuration);
                DotaGCHandler.Bootstrap(steamClient);
                dota = steamClient.GetHandler <DotaGCHandler>();

                // create the callback manager which will route callbacks to function calls
                manager = new CallbackManager(steamClient);

                // get the steamuser handler, which is used for logging on after successfully connecting
                steamUser = steamClient.GetHandler <SteamUser>();

                // register a few callbacks we're interested in
                // these are registered upon creation to a callback manager, which will then route the callbacks
                // to the functions specified
                manager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
                manager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnected);

                manager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn);
                manager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff);
                manager.Subscribe <SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
                manager.Subscribe <DotaGCHandler.BeginSessionResponse>(OnBeginSession);
                manager.Subscribe <DotaGCHandler.ConnectionStatus>(OnConnectionStatus);
                manager.Subscribe <DotaGCHandler.JoinChatChannelResponse>(OnJoinChatChannel);
                manager.Subscribe <DotaGCHandler.ChatChannelListResponse>(OnChatChannelList);
                manager.Subscribe <DotaGCHandler.GCWelcomeCallback>(OnDotaWelcome);

                isRunning = true;
                Console.WriteLine("Connecting to Steam...");

                // initiate the connection
                steamClient.Connect();
                while (isRunning)
                {
                    manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception occured: {ex.GetType()}: {ex.Message}");
                dotaIsReady = false;
                steamClient.Disconnect();
            }
            await Task.Delay(-1);
        }
Beispiel #41
0
 /// <summary>
 ///     Start connecting to the DOTA 2 game coordinator
 /// </summary>
 private void StartDotaGCConnection()
 {
     DotaGcHandler = SteamClient.GetHandler <DotaGCHandler>();
     DotaGcHandler.Start();
 }
Beispiel #42
0
 public void Setup()
 {
     Assume.That(() => SteamClient.Init(440000), Throws.Nothing);
 }
Beispiel #43
0
 /// <summary>
 /// Setup the DOTA 2 GC handler on an existing client.
 /// </summary>
 /// <param name="client"></param>
 public static void Bootstrap(SteamClient client)
 {
     client.AddHandler(new DotaGCHandler());
 }
Beispiel #44
0
        public Steam3Session(SteamUser.LogOnDetails details)
        {
            this.logonDetails = details;

            this.authenticatedUser          = details.Username != null;
            this.credentials                = new Credentials();
            this.bConnected                 = false;
            this.bConnecting                = false;
            this.bAborted                   = false;
            this.bExpectingDisconnectRemote = false;
            this.bDidDisconnect             = false;
            this.bDidReceiveLoginKey        = false;
            this.seq = 0;

            this.AppTickets       = new Dictionary <uint, byte[]>();
            this.AppTokens        = new Dictionary <uint, ulong>();
            this.PackageTokens    = new Dictionary <uint, ulong>();
            this.DepotKeys        = new Dictionary <uint, byte[]>();
            this.CDNAuthTokens    = new ConcurrentDictionary <string, TaskCompletionSource <SteamApps.CDNAuthTokenCallback> >();
            this.AppInfo          = new Dictionary <uint, SteamApps.PICSProductInfoCallback.PICSProductInfo>();
            this.PackageInfo      = new Dictionary <uint, SteamApps.PICSProductInfoCallback.PICSProductInfo>();
            this.AppBetaPasswords = new Dictionary <string, byte[]>();

            this.steamClient = new SteamClient();

            this.steamUser  = this.steamClient.GetHandler <SteamUser>();
            this.steamApps  = this.steamClient.GetHandler <SteamApps>();
            this.steamCloud = this.steamClient.GetHandler <SteamCloud>();
            var steamUnifiedMessages = this.steamClient.GetHandler <SteamUnifiedMessages>();

            this.steamPublishedFile = steamUnifiedMessages.CreateService <IPublishedFile>();

            this.callbacks = new CallbackManager(this.steamClient);

            this.callbacks.Subscribe <SteamClient.ConnectedCallback>(ConnectedCallback);
            this.callbacks.Subscribe <SteamClient.DisconnectedCallback>(DisconnectedCallback);
            this.callbacks.Subscribe <SteamUser.LoggedOnCallback>(LogOnCallback);
            this.callbacks.Subscribe <SteamUser.SessionTokenCallback>(SessionTokenCallback);
            this.callbacks.Subscribe <SteamApps.LicenseListCallback>(LicenseListCallback);
            this.callbacks.Subscribe <SteamUser.UpdateMachineAuthCallback>(UpdateMachineAuthCallback);
            this.callbacks.Subscribe <SteamUser.LoginKeyCallback>(LoginKeyCallback);

            Log.Info("Connecting to Steam3...");

            if (authenticatedUser)
            {
                FileInfo fi = new FileInfo(String.Format("{0}.sentryFile", logonDetails.Username));
                if (AccountSettingsStore.Instance.SentryData != null && AccountSettingsStore.Instance.SentryData.ContainsKey(logonDetails.Username))
                {
                    logonDetails.SentryFileHash = Util.SHAHash(AccountSettingsStore.Instance.SentryData[logonDetails.Username]);
                }
                else if (fi.Exists && fi.Length > 0)
                {
                    var sentryData = File.ReadAllBytes(fi.FullName);
                    logonDetails.SentryFileHash = Util.SHAHash(sentryData);
                    AccountSettingsStore.Instance.SentryData[logonDetails.Username] = sentryData;
                    AccountSettingsStore.Save();
                }
            }

            Connect();
        }
Beispiel #45
0
 private static void SetupDebugHook()
 {
     _mSteamApiWarningMessageHook = SteamAPIDebugTextHook;
     SteamClient.SetWarningMessageHook(_mSteamApiWarningMessageHook);
 }
Beispiel #46
0
 public void Update()
 {
     SteamClient.SteamClient_Cycle();
 }
Beispiel #47
0
        public static void Init()
        {
            if (!Steamworks.Load())
            {
                throw new SteamException("Unable to load steamclient library.");
            }

            if (SteamClient == null)
            {
                SteamClient = Steamworks.CreateInterface <ISteamClient009>();

                if (SteamClient == null)
                {
                    throw new SteamException("Unable to get ISteamClient interface.");
                }
            }

            if (Pipe == 0)
            {
                Pipe = SteamClient.CreateSteamPipe();

                if (Pipe == 0)
                {
                    throw new SteamException("Unable to create steam pipe.");
                }
            }

            if (User == 0)
            {
                User = SteamClient.ConnectToGlobalUser(Pipe);

                if (User == 0)
                {
                    throw new SteamException("Unable to connect to global user.");
                }
            }

            if (SteamUser == null)
            {
                SteamUser = SteamClient.GetISteamUser <ISteamUser015>(User, Pipe);

                if (SteamUser == null)
                {
                    throw new SteamException("Unable to get ISteamUser interface.");
                }
            }

            if (SteamFriends == null)
            {
                SteamFriends = SteamClient.GetISteamFriends <ISteamFriends009>(User, Pipe);

                if (SteamFriends == null)
                {
                    throw new SteamException("Unable to get ISteamFriends interface.");
                }
            }

            if (SteamApps == null)
            {
                SteamApps = SteamClient.GetISteamApps <ISteamApps001>(User, Pipe);

                if (SteamApps == null)
                {
                    throw new SteamException("Unable to get ISteamApps interface.");
                }
            }

            CallbackDispatcher.SpawnDispatchThread(Pipe);
        }
    public void RenderOnGUI()
    {
        GUILayout.BeginArea(new Rect(Screen.width - 200, 0, 200, Screen.height));
        GUILayout.Label("Variables:");
        GUILayout.Label("m_Pipe: " + m_Pipe);
        GUILayout.Label("m_GlobalUser: "******"m_LocalPipe: " + m_LocalPipe);
        GUILayout.Label("m_LocalUser: "******"box");
        m_ScrollPos = GUILayout.BeginScrollView(m_ScrollPos, GUILayout.Width(Screen.width - 215), GUILayout.Height(Screen.height - 33));

        GUILayout.Label("DON'T TOUCH THESE IF YOU DO NOT KNOW WHAT THEY DO, YOU COULD CRASH YOUR STEAM CLIENT");

        if (GUILayout.Button("CreateSteamPipe()"))
        {
            m_Pipe = SteamClient.CreateSteamPipe();
            print("SteamClient.CreateSteamPipe() : " + m_Pipe);
        }

        if (GUILayout.Button("BReleaseSteamPipe(m_Pipe)"))
        {
            bool ret = SteamClient.BReleaseSteamPipe(m_Pipe);
            print("SteamClient.BReleaseSteamPipe(" + m_Pipe + ") : " + ret);
        }

        if (GUILayout.Button("ConnectToGlobalUser(m_Pipe)"))
        {
            m_GlobalUser = SteamClient.ConnectToGlobalUser(m_Pipe);
            print("SteamClient.ConnectToGlobalUser(" + m_Pipe + ") : " + m_GlobalUser);
        }

        if (GUILayout.Button("CreateLocalUser(out m_LocalPipe, EAccountType.k_EAccountTypeGameServer)"))
        {
            m_LocalUser = SteamClient.CreateLocalUser(out m_LocalPipe, EAccountType.k_EAccountTypeGameServer);
            print("SteamClient.CreateLocalUser(" + "out m_LocalPipe" + ", " + EAccountType.k_EAccountTypeGameServer + ") : " + m_LocalUser + " -- " + m_LocalPipe);
        }

        if (GUILayout.Button("ReleaseUser(m_LocalPipe, m_LocalUser)"))
        {
            SteamClient.ReleaseUser(m_LocalPipe, m_LocalUser);
            print("SteamClient.ReleaseUser(" + m_LocalPipe + ", " + m_LocalUser + ")");
        }

        if (GUILayout.Button("GetISteamUser(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMUSER_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamUser(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMUSER_INTERFACE_VERSION);
            print("SteamClient.GetISteamUser(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMUSER_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamGameServer(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMGAMESERVER_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamGameServer(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMGAMESERVER_INTERFACE_VERSION);
            print("SteamClient.GetISteamGameServer(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMGAMESERVER_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("SetLocalIPBinding(TestConstants.k_IpAdress127_0_0_1, TestConstants.k_Port27015)"))
        {
            SteamClient.SetLocalIPBinding(TestConstants.k_IpAdress127_0_0_1, TestConstants.k_Port27015);
            print("SteamClient.SetLocalIPBinding(" + TestConstants.k_IpAdress127_0_0_1 + ", " + TestConstants.k_Port27015 + ")");
        }

        if (GUILayout.Button("GetISteamFriends(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMFRIENDS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamFriends(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMFRIENDS_INTERFACE_VERSION);
            print("SteamClient.GetISteamFriends(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMFRIENDS_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamUtils(SteamAPI.GetHSteamPipe(), Constants.STEAMUTILS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamUtils(SteamAPI.GetHSteamPipe(), Constants.STEAMUTILS_INTERFACE_VERSION);
            print("SteamClient.GetISteamUtils(" + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMUTILS_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamMatchmaking(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMATCHMAKING_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamMatchmaking(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMATCHMAKING_INTERFACE_VERSION);
            print("SteamClient.GetISteamMatchmaking(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMMATCHMAKING_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamMatchmakingServers(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMATCHMAKINGSERVERS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamMatchmakingServers(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMATCHMAKINGSERVERS_INTERFACE_VERSION);
            print("SteamClient.GetISteamMatchmakingServers(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMMATCHMAKINGSERVERS_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamGenericInterface(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMAPPTICKET_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamGenericInterface(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMAPPTICKET_INTERFACE_VERSION);
            print("SteamClient.GetISteamGenericInterface(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMAPPTICKET_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamUserStats(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMUSERSTATS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamUserStats(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMUSERSTATS_INTERFACE_VERSION);
            print("SteamClient.GetISteamUserStats(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMUSERSTATS_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamGameServerStats(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMGAMESERVERSTATS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamGameServerStats(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMGAMESERVERSTATS_INTERFACE_VERSION);
            print("SteamClient.GetISteamGameServerStats(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMGAMESERVERSTATS_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamApps(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMAPPS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamApps(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMAPPS_INTERFACE_VERSION);
            print("SteamClient.GetISteamApps(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMAPPS_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamNetworking(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMNETWORKING_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamNetworking(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMNETWORKING_INTERFACE_VERSION);
            print("SteamClient.GetISteamNetworking(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMNETWORKING_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamRemoteStorage(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMREMOTESTORAGE_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamRemoteStorage(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMREMOTESTORAGE_INTERFACE_VERSION);
            print("SteamClient.GetISteamRemoteStorage(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMREMOTESTORAGE_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamScreenshots(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMSCREENSHOTS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamScreenshots(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMSCREENSHOTS_INTERFACE_VERSION);
            print("SteamClient.GetISteamScreenshots(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMSCREENSHOTS_INTERFACE_VERSION + ") : " + ret);
        }

        GUILayout.Label("GetIPCCallCount() : " + SteamClient.GetIPCCallCount());

        //GUILayout.Label("SteamClient.SetWarningMessageHook : " + SteamClient.SetWarningMessageHook()); // N/A - Check out SteamTest.cs for example usage.

        if (GUILayout.Button("BShutdownIfAllPipesClosed()"))
        {
            bool ret = SteamClient.BShutdownIfAllPipesClosed();
            print("SteamClient.BShutdownIfAllPipesClosed() : " + ret);
        }

        if (GUILayout.Button("GetISteamHTTP(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMHTTP_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamHTTP(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMHTTP_INTERFACE_VERSION);
            print("SteamClient.GetISteamHTTP(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMHTTP_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamController(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMCONTROLLER_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamController(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMCONTROLLER_INTERFACE_VERSION);
            print("SteamClient.GetISteamController(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMCONTROLLER_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamUGC(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMUGC_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamUGC(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMUGC_INTERFACE_VERSION);
            print("SteamClient.GetISteamUGC(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMUGC_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamAppList(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMAPPLIST_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamAppList(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMAPPLIST_INTERFACE_VERSION);
            print("SteamClient.GetISteamAppList(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMAPPLIST_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamMusic(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMUSIC_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamMusic(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMUSIC_INTERFACE_VERSION);
            print("SteamClient.GetISteamMusic(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMMUSIC_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamMusicRemote(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMUSICREMOTE_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamMusicRemote(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMMUSICREMOTE_INTERFACE_VERSION);
            print("SteamClient.GetISteamMusicRemote(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMMUSICREMOTE_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamHTMLSurface(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMHTMLSURFACE_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamHTMLSurface(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMHTMLSURFACE_INTERFACE_VERSION);
            print("SteamClient.GetISteamHTMLSurface(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMHTMLSURFACE_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamInventory(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMINVENTORY_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamInventory(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMINVENTORY_INTERFACE_VERSION);
            print("SteamClient.GetISteamInventory(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMINVENTORY_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamVideo(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMVIDEO_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamVideo(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMVIDEO_INTERFACE_VERSION);
            print("SteamClient.GetISteamVideo(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMVIDEO_INTERFACE_VERSION + ") : " + ret);
        }

        if (GUILayout.Button("GetISteamParentalSettings(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMPARENTALSETTINGS_INTERFACE_VERSION)"))
        {
            System.IntPtr ret = SteamClient.GetISteamParentalSettings(SteamAPI.GetHSteamUser(), SteamAPI.GetHSteamPipe(), Constants.STEAMPARENTALSETTINGS_INTERFACE_VERSION);
            print("SteamClient.GetISteamParentalSettings(" + SteamAPI.GetHSteamUser() + ", " + SteamAPI.GetHSteamPipe() + ", " + Constants.STEAMPARENTALSETTINGS_INTERFACE_VERSION + ") : " + ret);
        }

        GUILayout.EndScrollView();
        GUILayout.EndVertical();
    }
Beispiel #49
0
 public void OnDestroy()
 {
     SteamClient.SteamClient_Shutdown();
 }
 internal void Setup(SteamClient client)
 {
     this.Client = client;
 }
Beispiel #51
0
    void Awake()
    {
        // Only one instance of Steamworks at a time!
        if (m_SteamTest != null)
        {
            Destroy(gameObject);
            return;
        }
        m_SteamTest = this;

        // We want our Steam Instance to persist across scenes.
        DontDestroyOnLoad(gameObject);

        if (!Packsize.Test())
        {
            throw new System.Exception("Packsize is wrong! You are likely using a Linux/OSX build on Windows or vice versa.");
        }

        if (!DllCheck.Test())
        {
            throw new System.Exception("DllCheck returned false.");
        }

        try {
            m_bInitialized = SteamAPI.Init();
        }
        catch (System.DllNotFoundException e) {         // We catch this exception here, as it will be the first occurrence of it.
            Debug.LogError("[Steamworks] Could not load [lib]steam_api.dll/so/dylib. It's likely not in the correct location. Refer to the README for more details.\n" + e, this);

            Application.Quit();
            return;
        }

        if (!m_bInitialized)
        {
            Debug.LogError("SteamAPI_Init() failed", this);
            return;
        }

        // Set up our callback to recieve warning messages from Steam.
        // You must launch with "-debug_steamapi" in the launch args to recieve warnings.
        SteamAPIWarningMessageHook = new SteamAPIWarningMessageHook_t(SteamAPIDebugTextHook);
        SteamClient.SetWarningMessageHook(SteamAPIWarningMessageHook);

        // Register our Steam Callbacks
        AppListTest            = gameObject.AddComponent <SteamAppListTest>();
        AppsTest               = gameObject.AddComponent <SteamAppsTest>();
        ClientTest             = gameObject.AddComponent <SteamClientTest>();
        ControllerTest         = gameObject.AddComponent <SteamControllerTest>();
        FriendsTest            = gameObject.AddComponent <SteamFriendsTest>();
        HTMLSurfaceTest        = gameObject.AddComponent <SteamHTMLSurfaceTest>();
        HTTPTest               = gameObject.AddComponent <SteamHTTPTest>();
        InventoryTest          = gameObject.AddComponent <SteamInventoryTest>();
        MatchmakingTest        = gameObject.AddComponent <SteamMatchmakingTest>();
        MatchmakingServersTest = gameObject.AddComponent <SteamMatchmakingServersTest>();
        MusicTest              = gameObject.AddComponent <SteamMusicTest>();
        MusicRemoteTest        = gameObject.AddComponent <SteamMusicRemoteTest>();
        NetworkingTest         = gameObject.AddComponent <SteamNetworkingTest>();
        ParentalSettingsTest   = gameObject.AddComponent <SteamParentalSettingsTest>();
        RemoteStorageTest      = gameObject.AddComponent <SteamRemoteStorageTest>();
        ScreenshotsTest        = gameObject.AddComponent <SteamScreenshotsTest>();
        UGCTest       = gameObject.AddComponent <SteamUGCTest>();
        UserTest      = gameObject.AddComponent <SteamUserTest>();
        UserStatsTest = gameObject.AddComponent <SteamUserStatsTest>();
        UtilsTest     = gameObject.AddComponent <SteamUtilsTest>();
        VideoTest     = gameObject.AddComponent <SteamVideoTest>();
    }
Beispiel #52
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            userHandlers = new Dictionary <SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximumActionGap     = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang           = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins     = config.Admins;
            ApiKey     = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if (config.LogLevel != null)
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile = config.LogFile;
            CreateLog();
            createHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            Log.Debug("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            botThread = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            botThread.DoWork             += BackgroundWorkerOnDoWork;
            botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            botThread.RunWorkerAsync();
        }
Beispiel #53
0
        /// <summary>
        ///     启动机器人实例
        /// </summary>
        /// <param name="startWait">是否等待三秒后再启动,默认 <c>false</c></param>
        public void Start(bool startWait = false)
        {
            lock (_startStopLock)
            {
                if (_disposed)
                {
                    _logger.Fatal($"#{SequenceNumber} Try to restart disposed bot.");
                    // throw new InvalidOperationException("Try to restart disposed bot.");
                }

                if (!_callbackPumpStarted)
                {
                    _callbackPumpStarted = true;
                    Task.Run(() =>
                    {
                        _logger.Info($"#{SequenceNumber} Listening callbacks...");
                        while (!_disposed)
                        {
                            _callbackManager.RunWaitAllCallbacks(TimeSpan.FromMilliseconds(10));
                        }
                        _logger.Info($"#{SequenceNumber} Stopped listening callbacks.");
                    });
                }

                try
                {
                    _coordinator.Consume(coordinator => coordinator.UpdateBot(Id, null, false, null));
                }
                catch (Exception e)
                {
                    _logger.Fatal($"#{SequenceNumber} Cannot clear online state before start : {e.Message}");
                    Restart();
                    return;
                }
                if (startWait)
                {
                    _logger.Info($"#{SequenceNumber} Starting in 3 seconds...");
                    Thread.Sleep(TimeSpan.FromSeconds(3));
                }

                var sfhPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data", $"{LogOnDetails.Username}.sfh");
                if (File.Exists(sfhPath))
                {
                    LogOnDetails.SentryFileHash = File.ReadAllBytes(sfhPath);
                    _logger.Info($"#{SequenceNumber} Use sentry file hash from {LogOnDetails.Username}.sfh.");
                }

                if (!_loginPending)
                {
                    LoginSemaphore.WaitOne();
                    _loginPending = true;
                }
                SteamClient.Connect();

                _mqChannel = _mqClientProvider.CreateModel();
                _mqChannel.BasicQos(0, 5, false);
                var queueName = MqClientProvider.SteamBotDelayedActionQueue(Id);
                _mqChannel.QueueDeclare(queueName, true, false, false, null);
                _mqChannel.QueueBind(queueName, MqClientProvider.DelayedMessageExchange, queueName);
                var consumer = new EventingBasicConsumer(_mqChannel);
                consumer.Received += OnDelayedActionReceived;
                _mqChannel.BasicConsume(queueName, false, consumer);
            }
        }
Beispiel #54
0
 public CallbackManagerFacts()
 {
     client = new SteamClient();
     mgr    = new CallbackManager(client);
 }
Beispiel #55
0
        static async Task RunOptions(Options opt)
        {
            SteamAuthenticationFilesProvider sentryFileProvider = default;

            if (!string.IsNullOrEmpty(opt.SentryDirectory))
            {
                sentryFileProvider = new DirectorySteamAuthenticationFilesProvider(opt.SentryDirectory);
            }

            if (opt.Username == Options.ANONYMOUS_USERNAME)
            {
                _steamCredentials = SteamCredentials.Anonymous;
            }
            else
            {
                _steamCredentials = new SteamCredentials(opt.Username, opt.Password);
            }

            _steamClient        = new SteamClient(_steamCredentials, new AuthCodeProvider(), sentryFileProvider);
            _steamContentClient = new SteamContentClient(_steamClient, null, opt.WorkerCount, opt.ChunkBufferSizeBytes, opt.ChunkBufferUsageThreshold);

            if (string.IsNullOrEmpty(opt.OS))
            {
                opt.OS = _steamClient.GetSteamOs().Identifier;
            }

            Console.Write($"Connecting to Steam as \"{opt.Username}\"... ");

            try
            {
                await _steamClient.ConnectAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed! Error: {ex.Message}");

                if (ex is SteamLogonException logonEx)
                {
                    if (logonEx.Result == SteamKit2.EResult.InvalidPassword)
                    {
                        Console.WriteLine($"Warning: The logon may have failed due to expired sentry-data. " +
                                          $"If you are sure that the provided username and password are correct, consider deleting the .bin and .key file for the user \"{_steamClient.Credentials.Username}\" in the sentries directory.");
                    }
                }

                Environment.Exit(3);
            }

            Console.WriteLine("OK.");

            if (opt.DownloadApp)
            {
                await DownloadApp(opt);
            }
            else if (opt.DownloadWorkshopItem)
            {
                await DownloadWorkshopItem(opt);
            }
            else
            {
                Console.WriteLine("No action to run specified, exiting.");
            }

            _steamClient.Shutdown();
        }
Beispiel #56
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Sample7: No username and password specified!");
                return;
            }

            // save our logon details
            user = args[0];
            pass = args[1];

            // create our steamclient instance
            steamClient = new SteamClient();
            // create the callback manager which will route callbacks to function calls
            manager = new CallbackManager(steamClient);

            // get the steamuser handler, which is used for logging on after successfully connecting
            steamUser = steamClient.GetHandler <SteamUser>();

            // register a few callbacks we're interested in
            // these are registered upon creation to a callback manager, which will then route the callbacks
            // to the functions specified
            manager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
            manager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnected);

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

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;

                Console.WriteLine("Received {0}, disconnecting...", e.SpecialKey);
                steamUser.LogOff();
            };

            var cellid = 0u;

            // if we've previously connected and saved our cellid, load it.
            if (File.Exists("cellid.txt"))
            {
                if (!uint.TryParse(File.ReadAllText("cellid.txt"), out cellid))
                {
                    Console.WriteLine("Error parsing cellid from cellid.txt. Continuing with cellid 0.");
                }
                else
                {
                    Console.WriteLine($"Using persisted cell ID {cellid}");
                }
            }

            SteamClient.Servers.CellID             = cellid;
            SteamClient.Servers.ServerListProvider = new FileStorageServerListProvider("servers_list.bin");

            isRunning = true;

            Console.WriteLine("Connecting to Steam...");

            // initiate the connection
            steamClient.Connect();

            // create our callback handling loop
            while (isRunning)
            {
                // in order for the callbacks to get routed, they need to be handled by the manager
                manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }
        }
        public static void Main(string[] args)
        {
            if (IsDebugRelease)
            {
                MessageBox.Show("Code messed up somewhere, report this to the devs, PROGRAM RUN IN DEBUG");
            }

            MainWindow.SetupSettings();
            if (!ProcessHelpers.IsVC2019x64Installed() && !Storage.Settings.ShownVCScreen)
            {
                MessageBox.Show(
                    "You do not have Visual C installed! Continue to install it.\nTHIS WILL NOT BE SHOWN AGAIN!\nDO NOT REPORT THE APP NOT RUNNING IF YOU DIDNT INSTALL THIS");
                Process.Start("https://aka.ms/vs/16/release/VC_redist.x64.exe");
                Storage.Settings.ShownVCScreen = true;
                throw new("Need Visual C Installed!");
            }

            var mtr = new List <Mod>();

            foreach (var a in (ModManifest.Instance * typeof(Mod)))
            {
                if (!File.Exists((ModManifest.Instance ^ a.Name).CanonicalLocation))
                {
                    mtr.Add(a);
                }
            }

            foreach (var remove in mtr)
            {
                ModManifest.Instance -= remove;
            }

            try {
                SteamClient.Init(960090);
                Storage.InstallDir = SteamApps.AppInstallDir();
                MelonHandler.EnsureMelonInstalled();
                FileAssociations.EnsureAssociationsSet();
            }
            catch (Exception e) {
                MessageBox.Show("ERROR 0x3ef93 PLEASE REPORT IN THE DISCORD" + Environment.NewLine + "Please include this message in your support ticket: " + e.Message);
                Environment.Exit(1);
            }

            _ = Directory.CreateDirectory(Storage.InstallDir + @"\Mods\Inferno");
            _ = Directory.CreateDirectory(Storage.InstallDir + @"\Mods\Inferno\Disabled");
            _ = Directory.CreateDirectory(Storage.InstallDir + @"\Mods");
            _ = Directory.CreateDirectory(Storage.InstallDir + @"\Mods\Disabled");
            _ = Directory.CreateDirectory(Environment.ExpandEnvironmentVariables("%AppData%\\InfernoOmnia\\"));
            if (args.Length != 0)
            {
                foreach (var file in args)
                {
                    if (!file.Contains(@"\Mods\Inferno"))
                    {
                        if (File.Exists(Storage.InstallDir + @"\Mods\Inferno\" + Path.GetFileName(file)))
                        {
                            File.Delete(Storage.InstallDir + @"\Mods\Inferno\" + Path.GetFileName(file));
                        }
                        File.Move(file, Storage.InstallDir + @"\Mods\Inferno\" + Path.GetFileName(file));
                    }
                }
            }

            if (Directory.GetFiles(Storage.InstallDir + @"\Mods\Inferno")
                .Combine(Directory.GetFiles(Storage.InstallDir + @"\Mods\Inferno\Disabled")).Length > 0)
            {
                var flag = false;
                foreach (var file in Directory.GetFiles(Storage.InstallDir + @"\Mods", "*.dll")
                         .Combine(Directory.GetFiles(Storage.InstallDir + @"\Mods\Inferno\Disabled")))
                {
                    MelonHandler.GetMelonAttrib(file, out var att);
                    if (att != null)
                    {
                        flag |= att.Name.Equals("Inferno API Injector");
                    }
                }

                if (!flag)
                {
                    File.Create(Storage.InstallDir + @"\Mods\Inferno API Injector.dll")
                    .Write(Resources.Inferno_API_Injector, 0, Resources.Inferno_API_Injector.Length);
                }
            }

            var app = new App {
                ShutdownMode = ShutdownMode.OnMainWindowClose
            };

            app.InitializeComponent();
            app.Run();
        }
Beispiel #58
0
 public override void OnEnter()
 {
     steamPipeId.Value = (int)SteamClient.CreateSteamPipe();
     Finish();
 }
Beispiel #59
0
 public SteamConnect()
 {
     steamClient = new SteamClient();
     callManager = new CallbackManager(steamClient);
 }
Beispiel #60
0
 public void TearDown()
 {
     SteamClient.Shutdown();
 }