예제 #1
0
		internal async Task OnNewConfigLoaded(ASF.BotConfigEventArgs args) {
			if (args == null) {
				Logging.LogNullError(nameof(args), BotName);
				return;
			}

			if (args.BotConfig == null) {
				Destroy();
				return;
			}

			if (args.BotConfig == BotConfig) {
				return;
			}

			try {
				if (args.BotConfig == BotConfig) {
					return;
				}

				Stop();
				BotConfig = args.BotConfig;

				CardsFarmer.Paused = BotConfig.Paused;

				if (BotConfig.AcceptConfirmationsPeriod > 0) {
					TimeSpan delay = TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod) + TimeSpan.FromMinutes(0.2 * Bots.Count);
					TimeSpan period = TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod);

					if (AcceptConfirmationsTimer == null) {
						AcceptConfirmationsTimer = new Timer(
							async e => await AcceptConfirmations(true).ConfigureAwait(false),
							null,
							delay, // Delay
							period // Period
						);
					} else {
						AcceptConfirmationsTimer.Change(delay, period);
					}
				} else {
					AcceptConfirmationsTimer?.Change(Timeout.Infinite, Timeout.Infinite);
					AcceptConfirmationsTimer?.Dispose();
				}

				if ((BotConfig.SendTradePeriod > 0) && (BotConfig.SteamMasterID != 0)) {
					TimeSpan delay = TimeSpan.FromHours(BotConfig.SendTradePeriod) + TimeSpan.FromMinutes(Bots.Count);
					TimeSpan period = TimeSpan.FromHours(BotConfig.SendTradePeriod);

					if (SendItemsTimer == null) {
						SendItemsTimer = new Timer(
							async e => await ResponseLoot(BotConfig.SteamMasterID).ConfigureAwait(false),
							null,
							delay, // Delay
							period // Period
						);
					} else {
						SendItemsTimer.Change(delay, period);
					}
				} else {
					SendItemsTimer?.Change(Timeout.Infinite, Timeout.Infinite);
					SendItemsTimer?.Dispose();
				}

				await Initialize().ConfigureAwait(false);
			} finally {
				InitializationSemaphore.Release();
			}
		}
예제 #2
0
			internal BotConfigEventArgs(BotConfig botConfig = null) {
				BotConfig = botConfig;
			}
예제 #3
0
		internal Bot(string botName) {
			if (string.IsNullOrEmpty(botName)) {
				throw new ArgumentNullException(nameof(botName));
			}

			if (Bots.ContainsKey(botName)) {
				throw new ArgumentException("That bot is already defined!");
			}

			string botPath = Path.Combine(SharedInfo.ConfigDirectory, botName);

			BotName = botName;
			SentryFile = botPath + ".bin";

			string botConfigFile = botPath + ".json";

			BotConfig = BotConfig.Load(botConfigFile);
			if (BotConfig == null) {
				Logging.LogGenericError("Your bot config is invalid, please verify content of " + botConfigFile + " and try again!", botName);
				return;
			}

			// Register bot as available for ASF
			if (!Bots.TryAdd(botName, this)) {
				throw new ArgumentException("That bot is already defined!");
			}

			string botDatabaseFile = botPath + ".db";

			BotDatabase = BotDatabase.Load(botDatabaseFile);
			if (BotDatabase == null) {
				Logging.LogGenericError("Bot database could not be loaded, refusing to create this bot instance! In order to recreate it, remove " + botDatabaseFile + " and try again!", botName);
				return;
			}

			if (BotDatabase.MobileAuthenticator != null) {
				BotDatabase.MobileAuthenticator.Init(this);
			} else {
				// Support and convert SDA files
				string maFilePath = botPath + ".maFile";
				if (File.Exists(maFilePath)) {
					ImportAuthenticator(maFilePath);
				}
			}

			// Initialize
			SteamClient = new SteamClient(Program.GlobalConfig.SteamProtocol);

			if (Program.GlobalConfig.Debug && Directory.Exists(SharedInfo.DebugDirectory)) {
				string debugListenerPath = Path.Combine(SharedInfo.DebugDirectory, botName);

				try {
					Directory.CreateDirectory(debugListenerPath);
					SteamClient.DebugNetworkListener = new NetHookNetworkListener(debugListenerPath);
				} catch (Exception e) {
					Logging.LogGenericException(e, botName);
				}
			}

			ArchiHandler = new ArchiHandler(this);
			SteamClient.AddHandler(ArchiHandler);

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

			SteamApps = SteamClient.GetHandler<SteamApps>();
			CallbackManager.Subscribe<SteamApps.FreeLicenseCallback>(OnFreeLicense);
			CallbackManager.Subscribe<SteamApps.GuestPassListCallback>(OnGuestPassList);
			CallbackManager.Subscribe<SteamApps.LicenseListCallback>(OnLicenseList);

			SteamFriends = SteamClient.GetHandler<SteamFriends>();
			CallbackManager.Subscribe<SteamFriends.ChatInviteCallback>(OnChatInvite);
			CallbackManager.Subscribe<SteamFriends.ChatMsgCallback>(OnChatMsg);
			CallbackManager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
			CallbackManager.Subscribe<SteamFriends.FriendMsgCallback>(OnFriendMsg);
			CallbackManager.Subscribe<SteamFriends.FriendMsgHistoryCallback>(OnFriendMsgHistory);
			CallbackManager.Subscribe<SteamFriends.PersonaStateCallback>(OnPersonaState);

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

			CallbackManager.Subscribe<ArchiHandler.NotificationsCallback>(OnNotifications);
			CallbackManager.Subscribe<ArchiHandler.OfflineMessageCallback>(OnOfflineMessage);
			CallbackManager.Subscribe<ArchiHandler.PlayingSessionStateCallback>(OnPlayingSessionState);
			CallbackManager.Subscribe<ArchiHandler.PurchaseResponseCallback>(OnPurchaseResponse);
			CallbackManager.Subscribe<ArchiHandler.SharedLibraryLockStatusCallback>(OnSharedLibraryLockStatus);

			ArchiWebHandler = new ArchiWebHandler(this);

			CardsFarmer = new CardsFarmer(this) {
				Paused = BotConfig.Paused
			};

			Trading = new Trading(this);

			HeartBeatTimer = new Timer(
				async e => await HeartBeat().ConfigureAwait(false),
				null,
				TimeSpan.FromMinutes(1) + TimeSpan.FromMinutes(0.2 * Bots.Count), // Delay
				TimeSpan.FromMinutes(1) // Period
			);

			Initialize().Forget();
		}
예제 #4
0
파일: ASF.cs 프로젝트: mzllu/ArchiSteamFarm
        private static async void OnChanged(object sender, FileSystemEventArgs e)
        {
            if ((sender == null) || (e == null))
            {
                ArchiLogger.LogNullError(nameof(sender) + " || " + nameof(e));
                return;
            }

            string botName = Path.GetFileNameWithoutExtension(e.Name);

            if (string.IsNullOrEmpty(botName))
            {
                return;
            }

            if (botName.Equals(SharedInfo.ASF))
            {
                ArchiLogger.LogGenericInfo(Strings.GlobalConfigChanged);
                await RestartOrExit().ConfigureAwait(false);

                return;
            }

            Bot bot;

            if (!Bot.Bots.TryGetValue(botName, out bot))
            {
                return;
            }

            DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);

            DateTime savedLastWriteTime;

            if (LastWriteTimes.TryGetValue(bot, out savedLastWriteTime))
            {
                if (savedLastWriteTime >= lastWriteTime)
                {
                    return;
                }
            }

            LastWriteTimes[bot] = lastWriteTime;

            // It's entirely possible that some process is still accessing our file, allow at least a second before trying to read it
            await Task.Delay(1000).ConfigureAwait(false);

            // It's also possible that we got some other event in the meantime
            if (LastWriteTimes.TryGetValue(bot, out savedLastWriteTime))
            {
                if (lastWriteTime != savedLastWriteTime)
                {
                    return;
                }

                if (LastWriteTimes.TryRemove(bot, out savedLastWriteTime))
                {
                    if (lastWriteTime != savedLastWriteTime)
                    {
                        return;
                    }
                }
            }

            bot.OnNewConfigLoaded(new BotConfigEventArgs(BotConfig.Load(e.FullPath))).Forget();
        }
예제 #5
0
파일: ASF.cs 프로젝트: mzllu/ArchiSteamFarm
 internal BotConfigEventArgs(BotConfig botConfig = null)
 {
     BotConfig = botConfig;
 }
예제 #6
0
        private static async Task <bool> HandleApiBotPost(HttpListenerRequest request, HttpListenerResponse response, string[] arguments, byte argumentsIndex)
        {
            if ((request == null) || (response == null) || (arguments == null) || (argumentsIndex == 0))
            {
                ASF.ArchiLogger.LogNullError(nameof(request) + " || " + nameof(response) + " || " + nameof(arguments) + " || " + nameof(argumentsIndex));
                return(false);
            }

            if (arguments.Length <= argumentsIndex)
            {
                return(false);
            }

            const string requiredContentType = "application/json";

            if (request.ContentType != requiredContentType)
            {
                await ResponseJsonObject(request, response, new GenericResponse(false, nameof(request.ContentType) + " must be declared as " + requiredContentType), HttpStatusCode.NotAcceptable).ConfigureAwait(false);

                return(true);
            }

            string body;

            using (StreamReader reader = new StreamReader(request.InputStream)) {
                body = await reader.ReadToEndAsync().ConfigureAwait(false);
            }

            if (string.IsNullOrEmpty(body))
            {
                await ResponseJsonObject(request, response, new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(body))), HttpStatusCode.BadRequest).ConfigureAwait(false);

                return(true);
            }

            BotRequest botRequest;

            try {
                botRequest = JsonConvert.DeserializeObject <BotRequest>(body);
            } catch (Exception e) {
                await ResponseJsonObject(request, response, new GenericResponse(false, string.Format(Strings.ErrorParsingObject, nameof(botRequest)) + Environment.NewLine + e), HttpStatusCode.BadRequest).ConfigureAwait(false);

                return(true);
            }

            string botName = WebUtility.UrlDecode(arguments[argumentsIndex]);

            if (botRequest.KeepSensitiveDetails && Bot.Bots.TryGetValue(botName, out Bot bot))
            {
                if (string.IsNullOrEmpty(botRequest.BotConfig.SteamLogin))
                {
                    botRequest.BotConfig.SteamLogin = bot.BotConfig.SteamLogin;
                }

                if (string.IsNullOrEmpty(botRequest.BotConfig.SteamParentalPIN))
                {
                    botRequest.BotConfig.SteamParentalPIN = bot.BotConfig.SteamParentalPIN;
                }

                if (string.IsNullOrEmpty(botRequest.BotConfig.SteamPassword))
                {
                    botRequest.BotConfig.SteamPassword = bot.BotConfig.SteamPassword;
                }
            }

            string filePath = Path.Combine(SharedInfo.ConfigDirectory, botName + ".json");

            if (!await BotConfig.Write(filePath, botRequest.BotConfig).ConfigureAwait(false))
            {
                await ResponseJsonObject(request, response, new GenericResponse(false, "Writing bot config failed, check ASF log for details"), HttpStatusCode.BadRequest).ConfigureAwait(false);

                return(true);
            }

            await ResponseJsonObject(request, response, new GenericResponse(true, "OK")).ConfigureAwait(false);

            return(true);
        }
예제 #7
0
		internal async Task<bool> Init(ulong steamID, EUniverse universe, string webAPIUserNonce, string parentalPin) {
			if ((steamID == 0) || (universe == EUniverse.Invalid) || string.IsNullOrEmpty(webAPIUserNonce) || string.IsNullOrEmpty(parentalPin)) {
				Logging.LogNullError(nameof(steamID) + " || " + nameof(universe) + " || " + nameof(webAPIUserNonce) + " || " + nameof(parentalPin), Bot.BotName);
				return false;
			}

			SteamID = steamID;

			string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));

			// Generate an AES session key
			byte[] sessionKey = SteamKit2.CryptoHelper.GenerateRandomBlock(32);

			// RSA encrypt it with the public key for the universe we're on
			byte[] cryptedSessionKey;
			using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(universe))) {
				cryptedSessionKey = rsa.Encrypt(sessionKey);
			}

			// Copy our login key
			byte[] loginKey = new byte[webAPIUserNonce.Length];
			Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length);

			// AES encrypt the loginkey with our session key
			byte[] cryptedLoginKey = SteamKit2.CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

			// Do the magic
			Logging.LogGenericInfo("Logging in to ISteamUserAuth...", Bot.BotName);

			KeyValue authResult;
			using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) {
				iSteamUserAuth.Timeout = Timeout;

				try {
					authResult = iSteamUserAuth.AuthenticateUser(
						steamid: steamID,
						sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)),
						encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)),
						method: WebRequestMethods.Http.Post,
						secure: !Program.GlobalConfig.ForceHttp
					);
				} catch (Exception e) {
					Logging.LogGenericException(e, Bot.BotName);
					return false;
				}
			}

			if (authResult == null) {
				Logging.LogNullError(nameof(authResult), Bot.BotName);
				return false;
			}

			string steamLogin = authResult["token"].Value;
			if (string.IsNullOrEmpty(steamLogin)) {
				Logging.LogNullError(nameof(steamLogin), Bot.BotName);
				return false;
			}

			string steamLoginSecure = authResult["tokensecure"].Value;
			if (string.IsNullOrEmpty(steamLoginSecure)) {
				Logging.LogNullError(nameof(steamLoginSecure), Bot.BotName);
				return false;
			}

            
        		string botPath = Path.Combine(SharedInfo.ConfigDirectory, Bot.BotName);
       		     	string botConfigFile = botPath + ".json";

            		BotConfig = BotConfig.Load(botConfigFile);

            		Dictionary<string, string> data = new Dictionary<string, string>(2) {
                		{ "sessionid", sessionID },
                		{ "selectedAvatar", BotConfig.AvatarID }
            		};
            		await WebBrowser.UrlPostRetry(BotConfig.AvatarLink, data).ConfigureAwait(false);


            		WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHost));
			WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamStoreHost));

			WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHost));
			WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamStoreHost));

			WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHost));
			WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamStoreHost));

			Logging.LogGenericInfo("Success!", Bot.BotName);

			// Unlock Steam Parental if needed
			if (!parentalPin.Equals("0")) {
				if (!await UnlockParentalAccount(parentalPin).ConfigureAwait(false)) {
					return false;
				}
			}

			Ready = true;
			LastSessionRefreshCheck = DateTime.Now;
			return true;
		}
예제 #8
0
		internal Bot(string botName) {
			if (string.IsNullOrEmpty(botName)) {
				throw new ArgumentNullException(nameof(botName));
			}

			if (Bots.ContainsKey(botName)) {
				throw new Exception("That bot is already defined!");
			}

			string botPath = Path.Combine(Program.ConfigDirectory, botName);

			BotName = botName;
			SentryFile = botPath + ".bin";

			BotConfig = BotConfig.Load(botPath + ".json");
			if (BotConfig == null) {
				Logging.LogGenericError("Your bot config is invalid, refusing to start this bot instance!", botName);
				return;
			}

			if (!BotConfig.Enabled) {
				Logging.LogGenericInfo("Not initializing this instance because it's disabled in config file", botName);
				return;
			}

			BotDatabase = BotDatabase.Load(botPath + ".db");
			if (BotDatabase == null) {
				Logging.LogGenericError("Bot database could not be loaded, refusing to start this bot instance!", botName);
				return;
			}

			// TODO: Converter code will be removed soon
			if (BotDatabase.SteamGuardAccount != null) {
				Logging.LogGenericWarning("Converting old ASF 2FA V2.0 format into new ASF 2FA V2.1 format...", botName);
				BotDatabase.MobileAuthenticator = MobileAuthenticator.LoadFromSteamGuardAccount(BotDatabase.SteamGuardAccount);
				Logging.LogGenericInfo("Done! If you didn't make a copy of your revocation code yet, then it's a good moment to do so: " + BotDatabase.SteamGuardAccount.RevocationCode, botName);
				Logging.LogGenericWarning("ASF will not keep this code anymore!", botName);
				BotDatabase.SteamGuardAccount = null;
			}

			if (BotDatabase.MobileAuthenticator != null) {
				BotDatabase.MobileAuthenticator.Init(this);
			} else {
				// Support and convert SDA files
				string maFilePath = botPath + ".maFile";
				if (File.Exists(maFilePath)) {
					ImportAuthenticator(maFilePath);
				}
			}

			// Initialize
			SteamClient = new SteamClient(Program.GlobalConfig.SteamProtocol);

			if (Program.GlobalConfig.Debug && !Debugging.NetHookAlreadyInitialized && Directory.Exists(Program.DebugDirectory)) {
				try {
					Debugging.NetHookAlreadyInitialized = true;
					SteamClient.DebugNetworkListener = new NetHookNetworkListener(Program.DebugDirectory);
				} catch (Exception e) {
					Logging.LogGenericException(e, botName);
				}
			}

			ArchiHandler = new ArchiHandler(this);
			SteamClient.AddHandler(ArchiHandler);

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

			SteamApps = SteamClient.GetHandler<SteamApps>();
			CallbackManager.Subscribe<SteamApps.FreeLicenseCallback>(OnFreeLicense);
			CallbackManager.Subscribe<SteamApps.GuestPassListCallback>(OnGuestPassList);

			SteamFriends = SteamClient.GetHandler<SteamFriends>();
			CallbackManager.Subscribe<SteamFriends.ChatInviteCallback>(OnChatInvite);
			CallbackManager.Subscribe<SteamFriends.ChatMsgCallback>(OnChatMsg);
			CallbackManager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
			CallbackManager.Subscribe<SteamFriends.FriendMsgCallback>(OnFriendMsg);
			CallbackManager.Subscribe<SteamFriends.FriendMsgHistoryCallback>(OnFriendMsgHistory);

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

			CallbackManager.Subscribe<ArchiHandler.NotificationsCallback>(OnNotifications);
			CallbackManager.Subscribe<ArchiHandler.OfflineMessageCallback>(OnOfflineMessage);
			CallbackManager.Subscribe<ArchiHandler.PlayingSessionStateCallback>(OnPlayingSessionState);
			CallbackManager.Subscribe<ArchiHandler.PurchaseResponseCallback>(OnPurchaseResponse);

			ArchiWebHandler = new ArchiWebHandler(this);
			CardsFarmer = new CardsFarmer(this);
			Trading = new Trading(this);

			if ((AcceptConfirmationsTimer == null) && (BotConfig.AcceptConfirmationsPeriod > 0)) {
				AcceptConfirmationsTimer = new Timer(
					async e => await AcceptConfirmations(true).ConfigureAwait(false),
					null,
					TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod), // Delay
					TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod) // Period
				);
			}

			if ((SendItemsTimer == null) && (BotConfig.SendTradePeriod > 0)) {
				SendItemsTimer = new Timer(
					async e => await ResponseLoot(BotConfig.SteamMasterID).ConfigureAwait(false),
					null,
					TimeSpan.FromHours(BotConfig.SendTradePeriod), // Delay
					TimeSpan.FromHours(BotConfig.SendTradePeriod) // Period
				);
			}

			// Register bot as available for ASF
			Bots[botName] = this;

			if (!BotConfig.StartOnLaunch) {
				return;
			}

			// Start
			Start().Forget();
		}
예제 #9
0
        // TODO: This should be removed soon
        internal static BotConfig LoadOldFormat(string path)
        {
            if (!File.Exists(path))
            {
                return(null);
            }

            BotConfig botConfig = new BotConfig();

            try {
                using (XmlReader reader = XmlReader.Create(path)) {
                    while (reader.Read())
                    {
                        if (reader.NodeType != XmlNodeType.Element)
                        {
                            continue;
                        }

                        string key = reader.Name;
                        if (string.IsNullOrEmpty(key))
                        {
                            continue;
                        }

                        string value = reader.GetAttribute("value");
                        if (string.IsNullOrEmpty(value))
                        {
                            continue;
                        }

                        switch (key)
                        {
                        case "Enabled":
                            botConfig.Enabled = bool.Parse(value);
                            break;

                        case "SteamLogin":
                            botConfig.SteamLogin = value;
                            break;

                        case "SteamPassword":
                            botConfig.SteamPassword = value;
                            break;

                        case "SteamApiKey":
                            botConfig.SteamApiKey = value;
                            break;

                        case "SteamTradeToken":
                            botConfig.SteamTradeToken = value;
                            break;

                        case "SteamParentalPIN":
                            botConfig.SteamParentalPIN = value;
                            break;

                        case "SteamMasterID":
                            botConfig.SteamMasterID = ulong.Parse(value);
                            break;

                        case "SteamMasterClanID":
                            botConfig.SteamMasterClanID = ulong.Parse(value);
                            break;

                        case "StartOnLaunch":
                            botConfig.StartOnLaunch = bool.Parse(value);
                            break;

                        case "UseAsfAsMobileAuthenticator":
                            botConfig.UseAsfAsMobileAuthenticator = bool.Parse(value);
                            break;

                        case "CardDropsRestricted":
                            botConfig.CardDropsRestricted = bool.Parse(value);
                            break;

                        case "FarmOffline":
                            botConfig.FarmOffline = bool.Parse(value);
                            break;

                        case "HandleOfflineMessages":
                            botConfig.HandleOfflineMessages = bool.Parse(value);
                            break;

                        case "ForwardKeysToOtherBots":
                            botConfig.ForwardKeysToOtherBots = bool.Parse(value);
                            break;

                        case "DistributeKeys":
                            botConfig.DistributeKeys = bool.Parse(value);
                            break;

                        case "ShutdownOnFarmingFinished":
                            botConfig.ShutdownOnFarmingFinished = bool.Parse(value);
                            break;

                        case "SendOnFarmingFinished":
                            botConfig.SendOnFarmingFinished = bool.Parse(value);
                            break;

                        case "SendTradePeriod":
                            botConfig.SendTradePeriod = byte.Parse(value);
                            break;

                        case "GamesPlayedWhileIdle":
                            botConfig.GamesPlayedWhileIdle.Clear();
                            foreach (string appID in value.Split(','))
                            {
                                botConfig.GamesPlayedWhileIdle.Add(uint.Parse(appID));
                            }
                            break;

                        case "Statistics":
                        case "Blacklist":
                        case "SteamNickname":
                            break;

                        default:
                            Logging.LogGenericWarning("Unrecognized config value: " + key + "=" + value);
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                Logging.LogGenericException(e);
                Logging.LogGenericError("Your config for this bot instance is invalid, it won't run!");
                return(null);
            }

            // Fixups for new format
            if (botConfig.SteamLogin != null && botConfig.SteamLogin.Equals("null"))
            {
                botConfig.SteamLogin = null;
            }

            if (botConfig.SteamPassword != null && botConfig.SteamPassword.Equals("null"))
            {
                botConfig.SteamPassword = null;
            }

            if (botConfig.SteamApiKey != null && botConfig.SteamApiKey.Equals("null"))
            {
                botConfig.SteamApiKey = null;
            }

            if (botConfig.SteamParentalPIN != null && botConfig.SteamParentalPIN.Equals("null"))
            {
                botConfig.SteamParentalPIN = null;
            }

            if (botConfig.SteamTradeToken != null && botConfig.SteamTradeToken.Equals("null"))
            {
                botConfig.SteamTradeToken = null;
            }

            return(botConfig);
        }
예제 #10
0
		internal Bot(string botName) {
			if (string.IsNullOrEmpty(botName)) {
				throw new ArgumentNullException("botName");
			}

			BotName = botName;

			string botPath = Path.Combine(Program.ConfigDirectory, botName);

			BotConfig = BotConfig.Load(botPath + ".json");
			if (BotConfig == null) {
				Logging.LogGenericError("Your bot config is invalid, refusing to start this bot instance!", botName);
				return;
			}

			if (!BotConfig.Enabled) {
				return;
			}

			BotDatabase = BotDatabase.Load(botPath + ".db");
			if (BotDatabase == null) {
				Logging.LogGenericError("Bot database could not be loaded, refusing to start this bot instance!", botName);
				return;
			}

			bool alreadyExists;
			lock (Bots) {
				alreadyExists = Bots.ContainsKey(botName);
				if (!alreadyExists) {
					Bots[botName] = this;
				}
			}

			if (alreadyExists) {
				return;
			}

			SentryFile = botPath + ".bin";

			if (BotDatabase.SteamGuardAccount == null) {
				// Support and convert SDA files
				string maFilePath = botPath + ".maFile";
				if (File.Exists(maFilePath)) {
					ImportAuthenticator(maFilePath);
				}
			}

			// Initialize
			SteamClient = new SteamClient(Program.GlobalConfig.SteamProtocol);

			if (Program.GlobalConfig.Debug && !Debugging.NetHookAlreadyInitialized && Directory.Exists(Program.DebugDirectory)) {
				try {
					SteamClient.DebugNetworkListener = new NetHookNetworkListener(Program.DebugDirectory);
					Debugging.NetHookAlreadyInitialized = true;
				} catch (Exception e) {
					Logging.LogGenericException(e, botName);
				}
			}

			ArchiHandler = new ArchiHandler(this);
			SteamClient.AddHandler(ArchiHandler);

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

			SteamApps = SteamClient.GetHandler<SteamApps>();
			CallbackManager.Subscribe<SteamApps.FreeLicenseCallback>(OnFreeLicense);
			CallbackManager.Subscribe<SteamApps.GuestPassListCallback>(OnGuestPassList);

			SteamFriends = SteamClient.GetHandler<SteamFriends>();
			CallbackManager.Subscribe<SteamFriends.ChatInviteCallback>(OnChatInvite);
			CallbackManager.Subscribe<SteamFriends.ChatMsgCallback>(OnChatMsg);
			CallbackManager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
			CallbackManager.Subscribe<SteamFriends.FriendMsgCallback>(OnFriendMsg);
			CallbackManager.Subscribe<SteamFriends.FriendMsgHistoryCallback>(OnFriendMsgHistory);

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

			CallbackManager.Subscribe<ArchiHandler.NotificationsCallback>(OnNotifications);
			CallbackManager.Subscribe<ArchiHandler.OfflineMessageCallback>(OnOfflineMessage);
			CallbackManager.Subscribe<ArchiHandler.PurchaseResponseCallback>(OnPurchaseResponse);

			ArchiWebHandler = new ArchiWebHandler(this);
			CardsFarmer = new CardsFarmer(this);
			Trading = new Trading(this);

			if (AcceptConfirmationsTimer == null && BotConfig.AcceptConfirmationsPeriod > 0) {
				AcceptConfirmationsTimer = new Timer(
					async e => await AcceptConfirmations(true).ConfigureAwait(false),
					null,
					TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod), // Delay
					TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod) // Period
				);
			}

			if (SendItemsTimer == null && BotConfig.SendTradePeriod > 0) {
				SendItemsTimer = new Timer(
					async e => await ResponseSendTrade(BotConfig.SteamMasterID).ConfigureAwait(false),
					null,
					TimeSpan.FromHours(BotConfig.SendTradePeriod), // Delay
					TimeSpan.FromHours(BotConfig.SendTradePeriod) // Period
				);
			}

			if (!BotConfig.StartOnLaunch) {
				return;
			}

			// Start
			Start().Forget();
		}