示例#1
0
        private static async Task InitGlobalDatabaseAndServices()
        {
            string globalDatabaseFile = ASF.GetFilePath(ASF.EFileType.Database);

            if (string.IsNullOrEmpty(globalDatabaseFile))
            {
                ASF.ArchiLogger.LogNullError(nameof(globalDatabaseFile));

                return;
            }

            if (!File.Exists(globalDatabaseFile))
            {
                ASF.ArchiLogger.LogGenericInfo(Strings.Welcome);
                await Task.Delay(10 * 1000).ConfigureAwait(false);

                ASF.ArchiLogger.LogGenericWarning(Strings.WarningPrivacyPolicy);
                await Task.Delay(5 * 1000).ConfigureAwait(false);
            }

            GlobalDatabase globalDatabase = await GlobalDatabase.CreateOrLoad(globalDatabaseFile).ConfigureAwait(false);

            if (globalDatabase == null)
            {
                ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorDatabaseInvalid, globalDatabaseFile));
                await Task.Delay(5 * 1000).ConfigureAwait(false);
                await Exit(1).ConfigureAwait(false);

                return;
            }

            ASF.InitGlobalDatabase(globalDatabase);

            // If debugging is on, we prepare debug directory prior to running
            if (Debugging.IsUserDebugging)
            {
                if (Debugging.IsDebugConfigured)
                {
                    ASF.ArchiLogger.LogGenericDebug(globalDatabaseFile + ": " + JsonConvert.SerializeObject(ASF.GlobalDatabase, Formatting.Indented));
                }

                Logging.EnableTraceLogging();

                if (Debugging.IsDebugConfigured)
                {
                    DebugLog.AddListener(new Debugging.DebugListener());
                    DebugLog.Enabled = true;

                    if (Directory.Exists(SharedInfo.DebugDirectory))
                    {
                        try {
                            Directory.Delete(SharedInfo.DebugDirectory, true);
                            await Task.Delay(1000).ConfigureAwait(false);                             // Dirty workaround giving Windows some time to sync
                        } catch (Exception e) {
                            ASF.ArchiLogger.LogGenericException(e);
                        }
                    }
                }

                try {
                    Directory.CreateDirectory(SharedInfo.DebugDirectory);
                } catch (Exception e) {
                    ASF.ArchiLogger.LogGenericException(e);
                }
            }

            WebBrowser.Init();
        }
示例#2
0
        internal static GlobalConfig Load(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                Logging.LogNullError(nameof(filePath));
                return(null);
            }

            if (!File.Exists(filePath))
            {
                return(null);
            }

            GlobalConfig globalConfig;

            try {
                globalConfig = JsonConvert.DeserializeObject <GlobalConfig>(File.ReadAllText(filePath));
            } catch (Exception e) {
                Logging.LogGenericException(e);
                return(null);
            }

            if (globalConfig == null)
            {
                Logging.LogNullError(nameof(globalConfig));
                return(null);
            }

            // SK2 supports only TCP and UDP steam protocols
            // Ensure that user can't screw this up
            switch (globalConfig.SteamProtocol)
            {
            case ProtocolType.Tcp:
            case ProtocolType.Udp:
                break;

            default:
                Logging.LogGenericWarning("Configured SteamProtocol is invalid: " + globalConfig.SteamProtocol + ". Value of " + DefaultSteamProtocol + " will be used instead");
                globalConfig.SteamProtocol = DefaultSteamProtocol;
                break;
            }

            // User might not know what he's doing
            // Ensure that he can't screw core ASF variables
            if (globalConfig.MaxFarmingTime == 0)
            {
                Logging.LogGenericWarning("Configured MaxFarmingTime is invalid: " + globalConfig.MaxFarmingTime + ". Value of " + DefaultMaxFarmingTime + " will be used instead");
                globalConfig.MaxFarmingTime = DefaultMaxFarmingTime;
            }

            if (globalConfig.FarmingDelay == 0)
            {
                Logging.LogGenericWarning("Configured FarmingDelay is invalid: " + globalConfig.FarmingDelay + ". Value of " + DefaultFarmingDelay + " will be used instead");
                globalConfig.FarmingDelay = DefaultFarmingDelay;
            }

            if (globalConfig.HttpTimeout == 0)
            {
                Logging.LogGenericWarning("Configured HttpTimeout is invalid: " + globalConfig.HttpTimeout + ". Value of " + DefaultHttpTimeout + " will be used instead");
                globalConfig.HttpTimeout = DefaultHttpTimeout;
            }

            if (globalConfig.WCFPort != 0)
            {
                return(globalConfig);
            }

            Logging.LogGenericWarning("Configured WCFPort is invalid: " + globalConfig.WCFPort + ". Value of " + DefaultWCFPort + " will be used instead");
            globalConfig.WCFPort = DefaultWCFPort;

            return(globalConfig);
        }
        internal async Task <bool> SendTradeOffer(List <Steam.Item> inventory, ulong partnerID, string token = null)
        {
            if (inventory == null || inventory.Count == 0 || partnerID == 0)
            {
                return(false);
            }

            string sessionID;

            if (!Cookie.TryGetValue("sessionid", out sessionID))
            {
                return(false);
            }

            List <Steam.TradeOfferRequest> trades = new List <Steam.TradeOfferRequest>(1 + inventory.Count / Trading.MaxItemsPerTrade);

            Steam.TradeOfferRequest singleTrade = null;
            for (ushort i = 0; i < inventory.Count; i++)
            {
                if (i % Trading.MaxItemsPerTrade == 0)
                {
                    if (trades.Count >= Trading.MaxTradesPerAccount)
                    {
                        break;
                    }

                    singleTrade = new Steam.TradeOfferRequest();
                    trades.Add(singleTrade);
                }

                Steam.Item item = inventory[i];
                singleTrade.me.assets.Add(new Steam.Item()
                {
                    appid     = "753",
                    contextid = "6",
                    amount    = item.amount,
                    assetid   = item.id
                });
            }

            string referer = "https://steamcommunity.com/tradeoffer/new";
            string request = referer + "/send";

            foreach (Steam.TradeOfferRequest trade in trades)
            {
                Dictionary <string, string> data = new Dictionary <string, string>(6)
                {
                    { "sessionid", sessionID },
                    { "serverid", "1" },
                    { "partner", partnerID.ToString() },
                    { "tradeoffermessage", "Sent by ASF" },
                    { "json_tradeoffer", JsonConvert.SerializeObject(trade) },
                    { "trade_offer_create_params", string.IsNullOrEmpty(token) ? "" : $"{{\"trade_offer_access_token\":\"{token}\"}}" }
                };

                HttpResponseMessage response = null;
                for (byte i = 0; i < WebBrowser.MaxRetries && response == null; i++)
                {
                    response = await WebBrowser.UrlPost(request, data, Cookie, referer).ConfigureAwait(false);
                }

                if (response == null)
                {
                    Logging.LogGenericWTF("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName);
                    return(false);
                }
            }

            return(true);
        }
        internal async Task <bool> Init(SteamClient steamClient, string webAPIUserNonce, string parentalPin)
        {
            if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce))
            {
                return(false);
            }

            SteamID = steamClient.SteamID;

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

            // Generate an AES session key
            byte[] sessionKey = 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(steamClient.ConnectedUniverse))) {
                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 = 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: true
                        );
                } catch (Exception e) {
                    Logging.LogGenericException(e, Bot.BotName);
                    return(false);
                }
            }

            if (authResult == null)
            {
                return(false);
            }

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

            string steamLogin       = authResult["token"].AsString();
            string steamLoginSecure = authResult["tokensecure"].AsString();

            Cookie["sessionid"]        = sessionID;
            Cookie["steamLogin"]       = steamLogin;
            Cookie["steamLoginSecure"] = steamLoginSecure;

            // The below is used for display purposes only
            Cookie["webTradeEligibility"] = "{\"allowed\":0,\"reason\":0,\"allowed_at_time\":0,\"steamguard_required_days\":0,\"sales_this_year\":0,\"max_sales_per_year\":0,\"forms_requested\":0}";

            await UnlockParentalAccount(parentalPin).ConfigureAwait(false);

            return(true);
        }
        internal List <Steam.TradeOffer> GetTradeOffers()
        {
            if (string.IsNullOrEmpty(Bot.BotConfig.SteamApiKey))
            {
                return(null);
            }

            KeyValue response = null;

            using (dynamic iEconService = WebAPI.GetInterface("IEconService", Bot.BotConfig.SteamApiKey)) {
                iEconService.Timeout = Timeout;

                for (byte i = 0; i < WebBrowser.MaxRetries && response == null; i++)
                {
                    try {
                        response = iEconService.GetTradeOffers(
                            get_received_offers: 1,
                            active_only: 1,
                            secure: true
                            );
                    } catch (Exception e) {
                        Logging.LogGenericException(e, Bot.BotName);
                    }
                }
            }

            if (response == null)
            {
                Logging.LogGenericWTF("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName);
                return(null);
            }

            List <Steam.TradeOffer> result = new List <Steam.TradeOffer>();

            foreach (KeyValue trade in response["trade_offers_received"].Children)
            {
                Steam.TradeOffer tradeOffer = new Steam.TradeOffer {
                    tradeofferid      = trade["tradeofferid"].AsString(),
                    accountid_other   = trade["accountid_other"].AsInteger(),
                    trade_offer_state = trade["trade_offer_state"].AsEnum <Steam.TradeOffer.ETradeOfferState>()
                };
                foreach (KeyValue item in trade["items_to_give"].Children)
                {
                    tradeOffer.items_to_give.Add(new Steam.Item {
                        appid      = item["appid"].AsString(),
                        contextid  = item["contextid"].AsString(),
                        assetid    = item["assetid"].AsString(),
                        classid    = item["classid"].AsString(),
                        instanceid = item["instanceid"].AsString(),
                        amount     = item["amount"].AsString(),
                    });
                }
                foreach (KeyValue item in trade["items_to_receive"].Children)
                {
                    tradeOffer.items_to_receive.Add(new Steam.Item {
                        appid      = item["appid"].AsString(),
                        contextid  = item["contextid"].AsString(),
                        assetid    = item["assetid"].AsString(),
                        classid    = item["classid"].AsString(),
                        instanceid = item["instanceid"].AsString(),
                        amount     = item["amount"].AsString(),
                    });
                }
                result.Add(tradeOffer);
            }

            return(result);
        }