Пример #1
0
        private async Task ResolveServerList()
        {
            DebugWrite("Resolving server list");

            IEnumerable <IPEndPoint> serverList = await ServerListProvider.FetchServerListAsync().ConfigureAwait(false);

            List <IPEndPoint> endpointList = serverList.ToList();

            if (endpointList.Count == 0 && canFetchDirectory)
            {
                DebugWrite("Server list provider had no entries, will query SteamDirectory");
                var directoryList = await SteamDirectory.LoadAsync(CellID).ConfigureAwait(false);

                endpointList = directoryList.ToList();
            }

            if (endpointList.Count == 0 && canFetchDirectory)
            {
                DebugWrite("Could not query SteamDirectory, falling back to cm0");
                var cm0 = await Dns.GetHostAddressesAsync("cm0.steampowered.com").ConfigureAwait(false);

                endpointList = cm0.Select(ipaddr => new IPEndPoint(ipaddr, 27015)).ToList();
            }

            DebugWrite("Resolved {0} servers", endpointList.Count);
            ReplaceList(endpointList);
        }
Пример #2
0
        /// <summary>
        /// Start the Bot
        /// If not all needed informations are given, end the Program
        /// Load the Steam's serverlist so we do not try to connect to an offline server
        /// Load the current bot sentryfile if it does exist, so we do not have to enter the E-Mail authcode everytime
        /// Start the connection to the SteamClient and start a never ending loop to listen to callbacks
        /// </summary>
        public void Start()
        {
            m_logger.Info("Connecting to Steam...");

            // Load the serverlist to get an available server to connect to
            // Prevent from trying to login to offline servers
            try
            {
                SteamDirectory.Initialize().Wait();
            }
            catch (Exception e)
            {
                m_logger.Warning("Failed to load serverlist with the message: " + e.Message);
            }

            FileInfo sentryFileInfo = new FileInfo($"Files/Authfiles/{m_steamUserLogonDetails.Username}.sentryfile");

            if (sentryFileInfo.Exists && sentryFileInfo.Length > 0)
            {
                m_steamUserLogonDetails.SentryFileHash = CryptoHelper.SHAHash(File.ReadAllBytes(sentryFileInfo.FullName));
            }

            // When the serverlist is loaded, try to connect to a server
            m_steamClient.Connect();

            // After a successful login check every second if we have a callback returned to us
            while (m_keepRunning)
            {
                m_callbackManager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }
        }
Пример #3
0
 /// <summary>
 /// This method should be used when we need to reconnect SteamClient, it'll allow us to keep things more organised
 /// </summary>
 private void Reconnect()
 {
     SteamDirectory.Initialize().Wait(15); //Update internal list that is heavily used before attempting login. And wait 2 Seconds to avoid Spam
                                           //IPEndPoint Address = new IPEndPoint(IPAddress.Parse("72.165.61.187"), 27017); //IF you ever need a sample address, use this
                                           // Console.WriteLine("CONNECTING:");
     steamClient.Connect();                //Lets try and log back in
 }
Пример #4
0
        void steam_connection()
        {
            SteamDirectory.Initialize();

            steamClient   = new SteamClient();
            steamWorkshop = new SteamWorkshop();

            steamClient.AddHandler(steamWorkshop);

            manager = new CallbackManager(steamClient);

            steamUser = steamClient.GetHandler <SteamUser>();

            manager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
            manager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn);
            manager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff);
            manager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnect);
            manager.Subscribe <SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
            manager.Subscribe <SteamUser.LoginKeyCallback>(OnLoginKey);

            steamClient.Connect();

            while (isRunning)
            {
                try {
                    manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
                }
                catch (Exception)
                {
                }
            }
        }
Пример #5
0
        private async Task ResolveServerList()
        {
            DebugWrite("Resolving server list");

            IEnumerable <ServerRecord> serverList = await configuration.ServerListProvider.FetchServerListAsync().ConfigureAwait(false);

            IReadOnlyCollection <ServerRecord> endpointList = serverList.ToList();

            if (endpointList.Count == 0 && configuration.AllowDirectoryFetch)
            {
                DebugWrite("Server list provider had no entries, will query SteamDirectory");
                endpointList = await SteamDirectory.LoadAsync(configuration).ConfigureAwait(false);
            }

            if (endpointList.Count == 0 && configuration.AllowDirectoryFetch)
            {
                DebugWrite("Could not query SteamDirectory, falling back to cm0");
                var cm0 = await Dns.GetHostAddressesAsync("cm0.steampowered.com").ConfigureAwait(false);

                endpointList = cm0.Select(ipaddr => ServerRecord.CreateSocketServer(new IPEndPoint(ipaddr, 27015))).ToList();
            }

            DebugWrite("Resolved {0} servers", endpointList.Count);
            ReplaceList(endpointList);
        }
Пример #6
0
 /// <summary>
 /// Connect to Steam
 /// </summary>
 private void Connect()
 {
     mIsRunning = true;
     mLog.Write(Log.LogLevel.Info, $"Connecting to Steam ...");
     SteamDirectory.Initialize().Wait();
     mSteam.client.Connect();
 }
Пример #7
0
        public static Config.UserInfo RetrieveInfo(string username, string password)
        {
            Class1.Username        = username;
            Class1.Password        = password;
            Class1.steamClient     = new SteamClient(ProtocolType.Tcp);
            Class1.callbackManager = new CallbackManager(Class1.steamClient);
            Class1.steamUser       = Class1.steamClient.GetHandler <SteamUser>();
            Class1.callbackManager.Subscribe <SteamClient.ConnectedCallback>(new Action <SteamClient.ConnectedCallback>(Class1.IsConnected));
            Class1.callbackManager.Subscribe <SteamClient.DisconnectedCallback>(new Action <SteamClient.DisconnectedCallback>(Class1.IsDisconnected));
            Class1.callbackManager.Subscribe <SteamUser.LoggedOnCallback>(new Action <SteamUser.LoggedOnCallback>(Class1.LogIn));
            Class1.callbackManager.Subscribe <SteamUser.LoggedOffCallback>(new Action <SteamUser.LoggedOffCallback>(Class1.LogOff));
            Class1.Running = true;

            // SteamDirectory
            SteamDirectory.Initialize(0u).Wait();
            Class1.steamClient.Connect(null);
            while (Class1.Running)
            {
                Class1.callbackManager.RunWaitCallbacks(TimeSpan.FromSeconds(3.0));
            }
            Config.UserInfo UserInfo = new Config.UserInfo();
            UserInfo.status  = Class1.statusStr;
            UserInfo.steamid = Convert.ToString(Class1.steamid);
            Class1.steamClient.Disconnect();

            return(UserInfo);
        }
Пример #8
0
 /// <summary>
 /// Connect to Steam
 /// </summary>
 private void Connect()
 {
     mIsRunning = true;
     Print("Connecting to steam ...", mInfo.Username);
     SteamDirectory.Initialize().Wait();
     mSteam.client.Connect();
 }
Пример #9
0
        private static async Task RegisterBots(StringComparer botsComparer)
        {
            if (botsComparer == null)
            {
                ArchiLogger.LogNullError(nameof(botsComparer));

                return;
            }

            if (Bot.Bots.Count > 0)
            {
                return;
            }

            // Ensure that we ask for a list of servers if we don't have any saved servers available
            IEnumerable <ServerRecord> servers = await GlobalDatabase.ServerListProvider.FetchServerListAsync().ConfigureAwait(false);

            if (servers?.Any() != true)
            {
                ArchiLogger.LogGenericInfo(string.Format(Strings.Initializing, nameof(SteamDirectory)));

                SteamConfiguration steamConfiguration = SteamConfiguration.Create(builder => builder.WithProtocolTypes(GlobalConfig.SteamProtocols).WithCellID(GlobalDatabase.CellID).WithServerListProvider(GlobalDatabase.ServerListProvider).WithHttpClientFactory(() => WebBrowser.GenerateDisposableHttpClient()));

                try {
                    await SteamDirectory.LoadAsync(steamConfiguration).ConfigureAwait(false);

                    ArchiLogger.LogGenericInfo(Strings.Success);
                } catch {
                    ArchiLogger.LogGenericWarning(Strings.BotSteamDirectoryInitializationFailed);
                    await Task.Delay(5000).ConfigureAwait(false);
                }
            }

            HashSet <string> botNames;

            try {
                botNames = Directory.EnumerateFiles(SharedInfo.ConfigDirectory, "*" + SharedInfo.ConfigExtension).Select(Path.GetFileNameWithoutExtension).Where(botName => !string.IsNullOrEmpty(botName) && IsValidBotName(botName)).ToHashSet(botsComparer);
            } catch (Exception e) {
                ArchiLogger.LogGenericException(e);

                return;
            }

            if (botNames.Count == 0)
            {
                ArchiLogger.LogGenericWarning(Strings.ErrorNoBotsDefined);

                return;
            }

            if (botNames.Count > MaximumRecommendedBotsCount)
            {
                ArchiLogger.LogGenericWarning(string.Format(Strings.WarningExcessiveBotsCount, MaximumRecommendedBotsCount));
                await Task.Delay(10000).ConfigureAwait(false);
            }

            await Utilities.InParallel(botNames.OrderBy(botName => botName).Select(Bot.RegisterBot)).ConfigureAwait(false);
        }
Пример #10
0
        void steam_connection()
        {
            uint cellid = 0;

            // 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.");
                    Log.w("Error parsing cellid from cellid.txt. Continuing with cellid 0.");
                    cellid = 0;
                }
                else
                {
                    Console.WriteLine($"Using persisted cell ID {cellid}");
                    Log.w($"Using persisted cell ID {cellid}");
                }
            }

            var config = SteamConfiguration.Create(b =>
                                                   b.WithCellID(cellid)
                                                   .WithServerListProvider(new FileStorageServerListProvider("servers_list.bin")));

            Log.w("Created new server list");

            steamClient = new SteamClient(config);
            Log.w("Creating client...");
            steamWorkshop = new SteamWorkshop();
            SteamDirectory.LoadAsync(config);
            Log.w("Loading steam directory");
            steamClient.AddHandler(steamWorkshop);

            manager = new CallbackManager(steamClient);

            steamUser = steamClient.GetHandler <SteamUser>();

            manager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
            manager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn);
            manager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff);
            manager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnect);
            manager.Subscribe <SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
            manager.Subscribe <SteamUser.LoginKeyCallback>(OnLoginKey);

            steamClient.Connect();
            Log.w("Connecting to steam...");
            while (isRunning)
            {
                try {
                    manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
                }
                catch (Exception)
                {
                }
            }
        }
Пример #11
0
        public void Connect()
        {
            Console.Error.WriteLine("Connecting...");
            SteamDirectory.Initialize().Wait();
            steam.Connect();

            while (!connected)
            {
                manager.RunWaitCallbacks(TimeSpan.FromMilliseconds(100));
            }
        }
Пример #12
0
 public void Connect()
 {
     //SteamClient.Servers.CellID = 148;
     //SteamClient.Servers.ServerListProvider = new FileStorageServerListProvider("servers_list.bin");
     SteamDirectory.Initialize().Wait();
     steamClient.Connect();
     while (!isStartOver)
     {
         // continue running callbacks until we get match details
         callbackMgr.RunWaitCallbacks(TimeSpan.FromSeconds(1));
     }
 }
Пример #13
0
        public static void LoadServers()
        {
            Log.WriteInfo("Steam", "Loading Steam servers...");

            var loadServersTask = SteamDirectory.Initialize(CellID);

            loadServersTask.Wait();

            if (loadServersTask.IsFaulted)
            {
                throw loadServersTask.Exception;
            }
        }
Пример #14
0
        private bool LoadServersList()
        {
            var loadServersTask = SteamDirectory.Initialize(0u);

            loadServersTask.Wait();

            if (loadServersTask.IsFaulted)
            {
                _logger.Info(String.Format("Error loading server list from directory: {0}", loadServersTask.Exception.Message));
                return(false);
            }
            return(true);
        }
Пример #15
0
        public void GetMatchMeta()
        {
            SteamDirectory.Initialize().Wait();

            var userinfo   = GetUserInfo();
            var gameClient = new DotaClient(userinfo.Username, userinfo.Password);

            gameClient.Connect();

            var controller = new MatchController(gameClient);
            var match      = controller.Get(3111014659);

            Assert.IsNotNull(match);
        }
Пример #16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Steam-Stack Chat Bridge launched.");
            if (File.Exists("config.ini"))
            {
                Console.WriteLine("config.ini found.");
                configfile = File.ReadAllLines("config.ini").ToList();
                if (configfile.Count() >= 6)
                {
                    Console.WriteLine("config.ini has enough lines, logging in to stack with mail " + configfile[0]);
                    var client = new Client(configfile[0], configfile[1]);
                    Console.WriteLine("Logged in. Joining room " + configfile[5]);
                    sandbox = client.JoinRoom(configfile[5]);

                    sandbox.EventManager.ConnectListener(EventType.InternalException, new Action <Exception>(ex => Console.WriteLine("[ERROR] " + ex)));

                    sandbox.EventManager.ConnectListener(EventType.MessagePosted, new Action <Message>(message =>
                    {
                        lastmessageno = message.ID;
                        steamFriends.SendChatMessage(new SteamID(configfile[4]), EChatEntryType.ChatMsg, string.Format("({2}) {0}: {1}", message.Author.Name, message.Content, message.ID));
                    }));

                    user         = configfile[2];
                    pass         = configfile[3];
                    steamClient  = new SteamClient();
                    manager      = new CallbackManager(steamClient);
                    steamUser    = steamClient.GetHandler <SteamUser>();
                    steamFriends = steamClient.GetHandler <SteamFriends>();
                    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 <SteamFriends.FriendMsgCallback>(OnMessage);
                    isRunning = true;

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

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

                    while (isRunning)
                    {
                        manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
                    }
                }
            }
        }
Пример #17
0
        /// <summary>
        /// Borrowed this part from
        /// https://github.com/JustArchi/ArchiSteamFarm
        /// </summary>
        /// <param name="cellId">steam cellid</param>
        /// <param name="serverList">list of cm servers</param>
        private void InitializeCMs(uint cellId, IServerListProvider serverList)
        {
            CMClient.Servers.CellID             = cellId;
            CMClient.Servers.ServerListProvider = serverList;
            Console.WriteLine("Initializing SteamDirectory ...");

            try
            {
                SteamDirectory.Initialize(cellId).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error configuring CM. Connecting might take longer than usual. {ex.Message}");
            }
        }
Пример #18
0
        public static void LoadServers()
        {
            Log.WriteInfo("Steam", "Loading Steam servers...");

            var loadServersTask = SteamDirectory.Initialize(CellID);

            TaskManager.RegisterErrorHandler(loadServersTask);

            loadServersTask.Wait();

            if (loadServersTask.IsFaulted)
            {
                Environment.Exit(1);
            }
        }
Пример #19
0
        public static void Main(string[] args)
        {
            SteamDirectory.Initialize().Wait();

            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseSetting("detailedErrors", "true")
                       .UseIISIntegration()
                       .UseStartup <Startup>()
                       .CaptureStartupErrors(true)
                       .UseApplicationInsights()
                       .Build();

            host.Run();
        }
Пример #20
0
        private async Task UpdateCMListViaWebAPI()
        {
            Log.WriteInfo("Web API", "Updating CM list");

            try
            {
                var servers = (await SteamDirectory.LoadAsync(SharedConfig, int.MaxValue, CancellationToken.None)).ToList();

                Log.WriteInfo("Web API", "Got {0} CMs", servers.Count);

                UpdateCMList(servers);
            }
            catch (Exception e)
            {
                Log.WriteError("Web API", "{0}", e);
            }
        }
Пример #21
0
        static void Run(string[] args)
        {
            user = args[0];
            pass = args[1];

            steamClient = new SteamClient(System.Net.Sockets.ProtocolType.Tcp);
            manager     = new CallbackManager(steamClient);

            steamUser      = steamClient.GetHandler <SteamUser>();
            steamUserStats = steamClient.GetHandler <SteamUserStats>();

            manager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
            manager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnected);
            manager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn);
            manager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff);

            isRunning = true;

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

            loggedIn = false;

            SteamDirectory.Initialize().Wait();

            steamClient.Connect();

            while (!loggedIn)
            {
                manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
                if (!isRunning)
                {
                    return;
                }
            }

            uint   appid      = Convert.ToUInt32(args[2]);
            string lbListFile = args[3];

            foreach (string lbname in File.ReadLines(lbListFile))
            {
                if (!String.IsNullOrEmpty(lbname) && isRunning)
                {
                    DownloadLeaderboard(appid, lbname);
                }
            }
        }
Пример #22
0
        private async Task UpdateCMListViaWebAPI()
        {
            Log.WriteInfo("Updating CM list using webapi");

            try
            {
                var globalServers     = (await SteamDirectory.LoadAsync(SharedConfig, int.MaxValue, CancellationToken.None)).ToList();
                var chinaRealmServers = (await LoadChinaCMList(SharedConfig)).Where(s => !globalServers.Contains(s)).ToList();
                var servers           = globalServers.Concat(chinaRealmServers);

                Log.WriteInfo($"Got {globalServers.Count} servers plus {chinaRealmServers.Count} chinese servers");

                UpdateCMList(servers);
            }
            catch (Exception e)
            {
                Log.WriteError($"Web API Exception: {e}");
            }
        }
Пример #23
0
        public void Connect()
        {
            JobManager.Start();

            Log.WriteInfo("Steam", "Retrieving servers...");

            // zzz
            SteamDirectory.Initialize().ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    Log.WriteInfo("Steam", "Unable to retrieve servers: {0}", t.Exception);
                }

                Log.WriteInfo("Steam", "Connecting...");

                nextConnect = DateTime.Now;
            });
        }
Пример #24
0
        /// <summary>
        /// Connect the bot to Steam
        /// </summary>
        /// <param name="wait">If thread should wait for bot to be connected again</param>
        public void Connect(bool wait = false)
        {
            mIsRunning = true;
            SteamDirectory.Initialize().Wait();
            mSteam.Client.Connect();

            if (wait)
            {
                mLog.Write(Log.LogLevel.Info, $"Waiting for {mSettings.displayName} to connect before resuming thread");
                while (mBotState != BotState.Connected)
                {
                    if (mBotState == BotState.Error)
                    {
                        mLog.Write(Log.LogLevel.Error, $"Bot {mSettings.displayName} encountered an error when connecting.");
                        break;
                    }

                    Thread.Sleep(250);
                }
            }
        }
Пример #25
0
        public static void Main(string[] args)
        {
            //DebugLog.AddListener((level, msg) =>
            //{
            //    Console.WriteLine("[{0}] {1}", level, msg);
            //});

            if (args.Length < 2)
            {
                Console.WriteLine("GMPublish: No username and password specified!");
                return;
            }

            user = args[0];
            pass = args[1];

            SteamDirectory.Initialize().Wait();

            steamClient          = new SteamClient();
            manager              = new CallbackManager(steamClient);
            steamUser            = steamClient.GetHandler <SteamUser>();
            steamUnifiedMessages = steamClient.GetHandler <SteamUnifiedMessages>();

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

            Console.WriteLine("Connecting to Steam...");
            isRunning = true;
            steamClient.Connect();
            while (isRunning)
            {
                manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }
            Console.WriteLine("Done?");
            Console.ReadLine();
        }
Пример #26
0
        static public void InitSteamkit()
        {
            SteamDirectory.Initialize();

            SteamClient = new SteamClient();

            CallbackManager = new CallbackManager(SteamClient);

            CallbackManager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
            CallbackManager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnected);

            SteamUser = SteamClient.GetHandler <SteamUser>();
            CallbackManager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn);
            CallbackManager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff);
            CallbackManager.Subscribe <SteamUser.AccountInfoCallback>(OnAccountInfo);
            CallbackManager.Subscribe <SteamUser.LoginKeyCallback>(OnLoginKey);
            CallbackManager.Subscribe <SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);

            SteamFriends = SteamClient.GetHandler <SteamFriends>();

            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            CallbackManager.Subscribe <SteamGameCoordinator.MessageCallback>(OnGCMessage);
        }
Пример #27
0
        public void Tick()
        {
            var loadServersTask = SteamDirectory.Initialize(0);

            loadServersTask.Wait();

            if (loadServersTask.IsFaulted)
            {
                Console.WriteLine("Error loading server list from directory: {0}", loadServersTask.Exception.Message);
                return;
            }

            Client.Connect();

            while (IsRunning)
            {
                CallbackManager.RunWaitCallbacks(TimeSpan.FromSeconds(5));

                if (IsLoggedOn)
                {
                    Apps.PICSGetChangesSince(PreviousChangeNumber, true, true);
                }
            }
        }
Пример #28
0
        public static int Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            Logger.Debug("Startup: Loading Titan Bootstrapper.");

            // Initialize Titan Singleton
            Instance = new Titan
            {
                Options = new Options()
            };

            Logger.Debug("Startup: Loading Serilog <-> Common Logging Bridge.");

            // Common Logging <-> Serilog bridge
            Log.Logger = LogCreator.Create("Quartz.NET Scheduler");

            Logger.Debug("Startup: Loading Quartz.NET.");

            // Quartz.NET
            Instance.Scheduler = StdSchedulerFactory.GetDefaultScheduler();
            Instance.Scheduler.Start();

            // SteamKit
            Logger.Debug("Startup: Refreshing Steam Universe list.");

            SteamDirectory.Initialize().Wait();

            Logger.Debug("Startup: Parsing Command Line Arguments.");

            /* Parse arguments provided with the starting of this */
            if (Parser.Default.ParseArguments(args, Instance.Options))
            {
                Logger.Information("Skipping UI and going directly to botting - Target: {Target} - Match ID: {Id}", Instance.Options.Target, Instance.Options.MatchId);
                Instance.EnableUI = false;
            }
            else
            {
                Logger.Information("The arguments --target and --mode were omitted - opening the UI.");
                Instance.EnableUI = true;
            }

            Logger.Debug("Startup: Initializing Gui Manager, Victim Tracker, Account Manager and Ban Manager.");

            Instance.UIManager = new UIManager();

            Instance.VictimTracker = new VictimTracker();

            // Schedule Victim Tracking
            Instance.Scheduler.ScheduleJob(Instance.VictimTracker.Job, Instance.VictimTracker.Trigger);

            var file = string.IsNullOrEmpty(Instance.Options.File) ? "accounts.json" : Instance.Options.File;

            Instance.AccountManager = new AccountManager(new FileInfo(Path.Combine(Environment.CurrentDirectory, file)));

            Instance.ThreadManager = new ThreadManager();

            Instance.BanManager = new BanManager();
            Instance.BanManager.ParseApiKeyFile();

            Logger.Debug("Startup: Registering Shutdown Hook.");

            // Register hook
            AppDomain.CurrentDomain.ProcessExit += OnShutdown;

            Logger.Debug("Startup: Parsing accounts.json file.");

            if (Instance.AccountManager.ParseAccountFile())
            {
                Logger.Information("Hello and welcome to Titan v1.4.0-Dev.");

                if (Instance.EnableUI)
                {
                    Instance.UIManager.ShowForm(UIType.Main);
                }
                else
                {
                    var mode = BotModeParser.Parse(Instance.Options.Mode);

                    if (mode == BotMode.Report)
                    {
                        Instance.AccountManager.StartBotting(mode, SteamUtil.Parse(Instance.Options.Target),
                                                             Instance.Options.MatchId != null ? Convert.ToUInt64(Instance.Options.MatchId) : 8);
                    }
                }

                Instance.UIManager.StartMainLoop();
            }

            // The Shutdown handler gets only called after the last thread finished.
            // Quartz runs a Watchdog until Scheduler#Shutdown is called, so we're calling it
            // before Titan will be calling the Shutdown Hook.
            Logger.Debug("Shutdown: Shutting down Quartz.NET Scheduler.");

            Instance.Scheduler.Shutdown();

            return(0); // OK.
        }
Пример #29
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();
            };

            int cellid = 0;

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

            if (File.Exists("servers.bin"))
            {
                // last time we connected to Steam, we got a list of servers. that list is persisted below.
                // load that list of servers into the server list.
                // this is a very simplistic serialization, you're free to serialize the server list however
                // you like (json, xml, whatever).

                using (var fs = File.OpenRead("servers.bin"))
                    using (var reader = new BinaryReader(fs))
                    {
                        while (fs.Position < fs.Length)
                        {
                            var numAddressBytes = reader.ReadInt32();
                            var addressBytes    = reader.ReadBytes(numAddressBytes);
                            var port            = reader.ReadInt32();

                            var ipaddress = new IPAddress(addressBytes);
                            var endPoint  = new IPEndPoint(ipaddress, port);

                            CMClient.Servers.TryAdd(endPoint);
                        }
                    }
            }
            else
            {
                // since we don't have a list of servers saved, load the latest list of Steam servers
                // from the Steam Directory.
                var loadServersTask = SteamDirectory.Initialize(cellid);
                loadServersTask.Wait();

                if (loadServersTask.IsFaulted)
                {
                    Console.WriteLine("Error loading server list from directory: {0}", loadServersTask.Exception.Message);
                    return;
                }
            }

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

            // before we exit, save our current server list to disk.
            // this is a very simplistic serialization, you're free to serialize the server list however
            // you like (json, xml, whatever).
            using (var fs = File.OpenWrite("servers.bin"))
                using (var writer = new BinaryWriter(fs))
                {
                    foreach (var endPoint in CMClient.Servers.GetAllEndPoints())
                    {
                        var addressBytes = endPoint.Address.GetAddressBytes();
                        writer.Write(addressBytes.Length);
                        writer.Write(addressBytes);
                        writer.Write(endPoint.Port);
                    }
                }
        }
Пример #30
0
        /// <summary>
        /// Starts the bot
        /// </summary>
        /// <param name="_username"></param>
        /// <param name="_password"></param>
        /// <param name="cll"></param>
        /// <param name="fll"></param>
        /// <param name="_logFile"></param>
        /// <param name="_displayName"></param>
        /// <param name="_sentryFile"></param>
        public static void Start(string _username, string _password, string cll, string fll, string _logFile, string _displayName, string _sentryFile)
        {
            username    = _username;
            logFile     = _logFile;
            password    = _password;
            displayName = _displayName;
            sentryFile  = _sentryFile;
            CLL         = cll;
            FLL         = fll;

            if (!File.Exists(username + "/login.json"))
            {
                MessageBoxResult save = MessageBox.Show("Save login information to file?", "Save Data", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (save == MessageBoxResult.Yes)
                {
                    WriteData();
                }
            }

            if (sharedSecret != "")
            {
                steamGuardAccount.SharedSecret = sharedSecret;
            }

            SubForCB();

            if (Directory.Exists(username + "/triggers/") && Directory.GetFiles(username + "/triggers/").Length > 0)
            {
                if (triggers.Count > 0)
                {
                    List <BaseTrigger> oldTriggers = BaseTrigger.ReadTriggers();
                    List <BaseTrigger> newTriggers = triggers;

                    Log.Instance.Verbose("Saving triggers...");
                    int count = triggers.Count;
                    foreach (BaseTrigger trigger in newTriggers)
                    {
                        Log.Instance.Debug("Saving triggers, " + count + " left");
                        trigger.SaveTrigger();
                        Log.Instance.Silly("Trigger {0}/{1} saved", trigger.Name, trigger.Type.ToString());
                        count--;
                    }
                    Log.Instance.Verbose("Successfully read trigger data from " + username + "/triggers/ and from triggers window");

                    triggers = oldTriggers.Concat(newTriggers).ToList();
                }
                else
                {
                    Log.Instance.Verbose("Loading triggers...");
                    triggers = BaseTrigger.ReadTriggers();
                    Log.Instance.Verbose("Successfully read trigger data from " + username + "/triggers/");
                }
            }
            else
            {
                if (triggers.Count > 0)
                {
                    Log.Instance.Verbose("Saving triggers...");
                    int count = triggers.Count;
                    foreach (BaseTrigger trigger in triggers)
                    {
                        Log.Instance.Debug("Saving triggers, " + count + " left");
                        trigger.SaveTrigger(); // save new triggers to file
                        Log.Instance.Silly("Trigger {0}/{1} saved", trigger.Name, trigger.Type.ToString());
                        count--;
                    }
                    Log.Instance.Verbose("Successfully read trigger data from triggers window");
                }
            }

            isRunning = true;

            foreach (BaseTrigger trigger in triggers)
            {
                trigger.OnLoad();
            }

            Log.Instance.Silly("Updating SteamKit2 servers...");
            SteamDirectory.Initialize().Wait();

            Log.Instance.Verbose("Connecting to Steam...");
            Connect();

            while (isRunning)
            {
                manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }
        }