public static void GetSummaries(SteamWeb web, SessionData session, ulong[] steamids, SummaryCallback summariesCallback)
 {
     web.Request(ApiEndpoints.USER_SUMMARIES_URL + "?access_token=" + session.OAuthToken + "&steamids=" + string.Join(",", steamids.Select(steamid => steamid.ToString()).ToArray()), "GET", (response, code) =>
     {
         summariesCallback(code != HttpStatusCode.OK ? new Players() : JsonConvert.DeserializeObject <Players>(response ?? string.Empty));
     });
 }
        private void _getConfirmationDetails(SteamWeb web, Confirmation conf, ConfirmationCallback callback)
        {
            string url = ApiEndpoints.COMMUNITY_BASE + "/mobileconf/details/" + conf.ID + "?";

            this.GenerateConfirmationQueryParams(web, "details", queryString =>
            {
                url += queryString;

                var cookies = new CookieContainer();
                this.Session.AddCookies(cookies);
                this.GenerateConfirmationUrl(web, referer =>
                {
                    web.Request(url, "GET", null, cookies, (response, code) =>
                    {
                        if (string.IsNullOrEmpty(response) || code != HttpStatusCode.OK)
                        {
                            callback(null);
                            return;
                        }

                        var confResponse = JsonConvert.DeserializeObject <ConfirmationDetailsResponse>(response);
                        callback(confResponse);
                    });
                });
            });
        }
 public void GenerateConfirmationUrl(SteamWeb web, string tag, Callback callback)
 {
     this.GenerateConfirmationQueryParams(web, tag, queryString =>
     {
         callback(this.GenerateConfirmationUrl(queryString));
     });
 }
        private void _sendConfirmationAjax(SteamWeb web, Confirmation conf, string op, BCallback callback)
        {
            this.GenerateConfirmationQueryParams(web, op, queryParams =>
            {
                string url         = ApiEndpoints.COMMUNITY_BASE + "/mobileconf/ajaxop";
                string queryString = "?op=" + op + "&";
                queryString       += queryParams;
                queryString       += "&cid=" + conf.ID + "&ck=" + conf.Key;
                url += queryString;

                var cookies = new CookieContainer();
                this.Session.AddCookies(cookies);

                web.Request(url, "GET", null, cookies, (response, code) =>
                {
                    if (response == null || code != HttpStatusCode.OK)
                    {
                        callback(false);
                        return;
                    }

                    var confResponse = JsonConvert.DeserializeObject <SuccessResponse>(response);
                    callback(confResponse.Success);
                });
            });
        }
        public void GenerateConfirmationQueryParams(SteamWeb web, string tag, Callback callback)
        {
            if (string.IsNullOrEmpty(this.DeviceID))
            {
                throw new ArgumentException("Device ID is not present");
            }

            TimeAligner.GetSteamTime(web, time =>
            {
                callback("p=" + this.DeviceID + "&a=" + this.Session.SteamID.ToString() + "&k=" + this._generateConfirmationHashForTime(time, tag) + "&t=" + time + "&m=android&tag=" + tag);
            });
        }
        public void FetchConfirmations(SteamWeb web, FcCallback callback)
        {
            this.GenerateConfirmationUrl(web, url =>
            {
                var cookies = new CookieContainer();
                this.Session.AddCookies(cookies);

                web.Request(url, "GET", null, cookies, (response, code) =>
                {
                    var ret = new List <Confirmation>();
                    if (response == null || code != HttpStatusCode.OK)
                    {
                        // Forbidden = family view, NotFound = bad token
                        callback(ret, code == HttpStatusCode.Forbidden ? null : new WgTokenInvalidException());
                        return;
                    }

                    // Was it so hard?
                    var doc = new HtmlDocument();
                    doc.LoadHtml(response);

                    HtmlNode list = doc.GetElementbyId("mobileconf_list");
                    if (list == null || response.Contains("<div>Nothing to confirm</div>"))
                    {
                        callback(ret, null);
                        return;
                    }

                    IEnumerable <HtmlNode> entries = list.Descendants("div").Where(child => child.Attributes["class"]?.Value == "mobileconf_list_entry");

                    foreach (HtmlNode node in entries)
                    {
                        // Look now, html is complicated
                        string[] desc = node.Descendants("div").First(child => child.Attributes["class"].Value == "mobileconf_list_entry_description").Descendants("div").Select(elem => elem.InnerText).ToArray();
                        ret.Add(new Confirmation
                        {
                            Description     = desc[0],
                            Description2    = desc[1],
                            DescriptionTime = desc[2],
                            ID  = int.Parse(node.GetAttributeValue("data-confid", "0")),
                            Key = node.GetAttributeValue("data-key", "")
                        });
                    }

                    callback(ret, null);
                });
            });
        }
        public void GetConfirmationTradeOfferId(SteamWeb web, Confirmation conf, LongCallback callback)
        {
            this._getConfirmationDetails(web, conf, confDetails =>
            {
                if (confDetails == null || !confDetails.Success)
                {
                    callback(-1);
                    return;
                }

                var tradeOfferIdRegex = new Regex("<div class=\"tradeoffer\" id=\"tradeofferid_(\\d+)\" >");
                if (!tradeOfferIdRegex.IsMatch(confDetails.Html))
                {
                    callback(-1);
                    return;
                }
                callback(long.Parse(tradeOfferIdRegex.Match(confDetails.Html).Groups[1].Value));
            });
        }
        /// <summary>
        ///     Refreshes the Steam session. Necessary to perform confirmations if your session has expired or changed.
        /// </summary>
        /// <returns></returns>
        public void RefreshSession(SteamWeb web, BfCallback callback)
        {
            string url      = ApiEndpoints.MOBILEAUTH_GETWGTOKEN;
            var    postData = new Dictionary <string, string>();

            postData.Add("access_token", this.Session.OAuthToken);

            web.Request(url, "POST", postData, (response, code) =>
            {
                if (response == null || code != HttpStatusCode.OK)
                {
                    callback(Success.Error);
                    return;
                }

                try
                {
                    var refreshResponse = JsonConvert.DeserializeObject <WebResponse <RefreshSessionDataResponse> >(response);
                    if (string.IsNullOrEmpty(refreshResponse?.Response?.Token))
                    {
                        callback(Success.Failure);
                        return;
                    }

                    string token       = this.Session.SteamID + "%7C%7C" + refreshResponse.Response.Token;
                    string tokenSecure = this.Session.SteamID + "%7C%7C" + refreshResponse.Response.TokenSecure;

                    this.Session.SteamLogin       = token;
                    this.Session.SteamLoginSecure = tokenSecure;
                    Storage.PushStore(this.Session);

                    callback(Success.Success);
                }
                catch (Exception)
                {
                    callback(Success.Error);
                }
            });
        }
        public void DeactivateAuthenticator(SteamWeb web, int scheme, BCallback callback)
        {
            var postData = new Dictionary <string, string>();

            postData.Add("steamid", this.Session.SteamID.ToString());
            postData.Add("steamguard_scheme", scheme.ToString());
            postData.Add("revocation_code", this.RevocationCode);
            postData.Add("access_token", this.Session.OAuthToken);

            web.MobileLoginRequest(ApiEndpoints.STEAMAPI_BASE + "/ITwoFactorService/RemoveAuthenticator/v0001", "POST", postData, (res, code) =>
            {
                try
                {
                    var removeResponse = JsonConvert.DeserializeObject <WebResponse <UnlinkResponse> >(res);

                    callback(removeResponse?.Response != null && (removeResponse.Response.Success || removeResponse.Response.AttemptsRemaining > 0));
                }
                catch (Exception)
                {
                    callback(false);
                }
            });
        }
        public void DoLogin(SteamWeb web, LoginCallback callback)
        {
            var             postData = new Dictionary <string, string>();
            CookieContainer cookies  = this._cookies;

            WebCallback hasCookies = (res, code) =>
            {
                postData.Add("username", this.Username);
                web.MobileLoginRequest(ApiEndpoints.COMMUNITY_BASE + "/login/getrsakey", "POST", postData, cookies, (rsaRawResponse, rsaCode) =>
                {
                    if (rsaRawResponse == null || rsaCode != HttpStatusCode.OK || rsaRawResponse.Contains("<BODY>\nAn error occurred while processing your request."))
                    {
                        callback(LoginResult.GeneralFailure);
                        return;
                    }

                    var rsaResponse = JsonConvert.DeserializeObject <RSAResponse>(rsaRawResponse);

                    if (!rsaResponse.Success)
                    {
                        callback(LoginResult.BadRsa);
                        return;
                    }

                    var mod           = new BigInteger(rsaResponse.Modulus, 16);
                    var exp           = new BigInteger(rsaResponse.Exponent, 16);
                    var encryptEngine = new Pkcs1Encoding(new RsaEngine());
                    var rsaParams     = new RsaKeyParameters(false, mod, exp);

                    encryptEngine.Init(true, rsaParams);

                    byte[] passwordArr       = Encoding.UTF8.GetBytes(this.Password);
                    string encryptedPassword = Convert.ToBase64String(encryptEngine.ProcessBlock(passwordArr, 0, passwordArr.Length));

                    postData.Clear();
                    postData.Add("username", this.Username);
                    postData.Add("password", encryptedPassword);

                    postData.Add("twofactorcode", this.TwoFactorCode ?? "");

                    postData.Add("captchagid", this.RequiresCaptcha ? this.CaptchaGID : "-1");
                    postData.Add("captcha_text", this.RequiresCaptcha ? this.CaptchaText : "");

                    postData.Add("emailsteamid", this.Requires2FA || this.RequiresEmail ? this.SteamID.ToString() : "");
                    postData.Add("emailauth", this.RequiresEmail ? this.EmailCode : "");

                    postData.Add("rsatimestamp", rsaResponse.Timestamp);
                    postData.Add("remember_login", "false");
                    postData.Add("oauth_client_id", "DE45CD61");
                    postData.Add("oauth_scope", "read_profile write_profile read_client write_client");
                    postData.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile");
                    postData.Add("donotcache", Util.GetSystemUnixTime().ToString());

                    web.MobileLoginRequest(ApiEndpoints.COMMUNITY_BASE + "/login/dologin", "POST", postData, cookies, (rawLoginResponse, loginCode) =>
                    {
                        LoginResponse loginResponse = null;

                        if (rawLoginResponse != null && loginCode == HttpStatusCode.OK)
                        {
                            loginResponse = JsonConvert.DeserializeObject <LoginResponse>(rawLoginResponse);
                        }

                        if (loginResponse == null)
                        {
                            callback(LoginResult.GeneralFailure);
                            return;
                        }

                        if (loginResponse.Message != null && loginResponse.Message.Contains("Incorrect login"))
                        {
                            callback(LoginResult.BadCredentials);
                            return;
                        }

                        if (loginResponse.CaptchaNeeded)
                        {
                            this.RequiresCaptcha = true;
                            this.CaptchaGID      = loginResponse.CaptchaGid;
                            callback(LoginResult.NeedCaptcha);
                            return;
                        }

                        if (loginResponse.EmailAuthNeeded)
                        {
                            this.RequiresEmail = true;
                            this.SteamID       = loginResponse.EmailSteamId;
                            callback(LoginResult.NeedEmail);
                            return;
                        }

                        if (loginResponse.TwoFactorNeeded && !loginResponse.Success)
                        {
                            this.Requires2FA = true;
                            callback(LoginResult.Need2Fa);
                            return;
                        }

                        if (loginResponse.Message != null && loginResponse.Message.Contains("too many login failures"))
                        {
                            callback(LoginResult.TooManyFailedLogins);
                            return;
                        }

                        if (string.IsNullOrEmpty(loginResponse.OAuthData?.OAuthToken))
                        {
                            callback(LoginResult.GeneralFailure);
                            return;
                        }

                        if (!loginResponse.LoginComplete)
                        {
                            callback(LoginResult.BadCredentials);
                            return;
                        }

                        CookieCollection readableCookies = cookies.GetCookies(new Uri("https://steamcommunity.com"));
                        OAuth oAuthData = loginResponse.OAuthData;

                        this.Session = new SessionData
                        {
                            OAuthToken       = oAuthData.OAuthToken,
                            SteamID          = oAuthData.SteamId,
                            SteamLogin       = oAuthData.SteamId + "%7C%7C" + oAuthData.SteamLogin,
                            SteamLoginSecure = oAuthData.SteamId + "%7C%7C" + oAuthData.SteamLoginSecure,
                            WebCookie        = oAuthData.Webcookie,
                            SessionID        = readableCookies["sessionid"].Value,
                            Username         = this.Username
                        };
                        this.LoggedIn = true;
                        callback(LoginResult.LoginOkay);
                    });
                });
            };

            if (cookies.Count == 0)
            {
                //Generate a SessionID
                const string url = "https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client";
                cookies.Add(SteamWeb.uri, new Cookie("mobileClientVersion", "0 (2.1.3)", "/"));
                cookies.Add(SteamWeb.uri, new Cookie("mobileClient", "android", "/"));
                cookies.Add(SteamWeb.uri, new Cookie("Steam_Language", "english", "/"));

                var headers = new WebHeaderCollection
                {
                    ["X-Requested-With"] = "com.valvesoftware.android.steam.community"
                };

                web.MobileLoginRequest(url, "GET", null, cookies, headers, hasCookies);
            }
            else
            {
                hasCookies("", HttpStatusCode.OK);
            }
        }
 public void GenerateConfirmationUrl(SteamWeb web, Callback callback)
 {
     // Default tag = conf
     this.GenerateConfirmationUrl(web, "conf", callback);
 }
 public void DenyConfirmation(SteamWeb web, Confirmation conf, BCallback callback)
 {
     this._sendConfirmationAjax(web, conf, "cancel", callback);
 }
 public void AcceptConfirmation(SteamWeb web, Confirmation conf, BCallback callback)
 {
     this._sendConfirmationAjax(web, conf, "allow", callback);
 }
 public void DeactivateAuthenticator(SteamWeb web, BCallback callback)
 {
     // Default scheme = 2
     this.DeactivateAuthenticator(web, 2, callback);
 }