Ejemplo n.º 1
0
        public TradeHistoryResponse GetTradeHistory(int?maxTrades, long?startAfterTime, string startAfterTradeId,
                                                    bool navigatingBack = false, bool getDescriptions = false, string lanugage = "en",
                                                    bool includeFailed  = false)
        {
            if (!string.IsNullOrEmpty(startAfterTradeId))
            {
                startAfterTime = null;
            }

            var options = GetOptions(
                ("key", _apiKey),
                ("max_trades", maxTrades),
                ("start_after_tradeid", startAfterTradeId),
                ("get_descriptions", BoolConverter(getDescriptions)),
                ("language", lanugage),
                ("include_failed", BoolConverter(includeFailed)),
                ("start_after_time", startAfterTime),
                ("navigating_back", BoolConverter(navigatingBack))
                );

            var url      = string.Format(BaseUrl, "GetTradeHistory", "v1", options);
            var response = SteamWeb.Request(url, "GET", data: null);

            try
            {
                var result = JsonConvert.DeserializeObject <ApiResponse <TradeHistoryResponse> >(response);
                return(result.Response);
            }
            catch (Exception ex)
            {
                Logger.Error("Error on get trade history", ex);
            }

            return(new TradeHistoryResponse());
        }
Ejemplo n.º 2
0
        public OffersResponse GetTradeOffers(bool getSentOffers, bool getReceivedOffers, bool getDescriptions,
                                             bool activeOnly, bool historicalOnly, string timeHistoricalCutoff = "1389106496", string language = "en_us")
        {
            if (!getSentOffers && !getReceivedOffers)
            {
                throw new ArgumentException("getSentOffers and getReceivedOffers can't be both false");
            }

            var options = string.Format(
                "?key={0}&get_sent_offers={1}&get_received_offers={2}&get_descriptions={3}&language={4}&active_only={5}&historical_only={6}",
                _apiKey, BoolConverter(getSentOffers), BoolConverter(getReceivedOffers), BoolConverter(getDescriptions),
                language, BoolConverter(activeOnly), BoolConverter(historicalOnly));

            if (timeHistoricalCutoff != "1389106496")
            {
                options += $"&time_historical_cutoff={timeHistoricalCutoff}";
            }


            var url      = string.Format(BaseUrl, "GetTradeOffers", "v1", options);
            var response = SteamWeb.Request(url, "GET", data: null);

            try
            {
                var result = JsonConvert.DeserializeObject <ApiResponse <OffersResponse> >(response);
                return(result.Response);
            }
            catch (Exception ex)
            {
                Logger.Error("Error on get rdade offers", ex);
            }

            return(new OffersResponse());
        }
Ejemplo n.º 3
0
        public static void BreakOnGems(string sessionId, string appId, string assetId, string contextId, int expectedGemsValue, ulong steamId, CookieContainer cookies, WebProxy proxy)
        {
            var response = SteamWeb.Request(
                $"https://steamcommunity.com/profiles/{steamId}/ajaxgrindintogoo/",
                "POST",
                new NameValueCollection
            {
                { "sessionid", sessionId },
                { "appid", appId },
                { "assetid", assetId },
                { "contextid", contextId },
                { "goo_value_expected", expectedGemsValue.ToString() },
            },
                cookies,
                referer: $"https://steamcommunity.com/profiles/{steamId}/inventory/",
                proxy: proxy);

            if (response == null)
            {
                throw new WebException("Steam response is empty");
            }

            var json = JsonConvert.DeserializeObject <BreakGemsResponse>(response);

            if (json.Success != 1)
            {
                throw new WebException($"Response success is {json.Success}");
            }
        }
Ejemplo n.º 4
0
        public MyInventoryRootModel LoadMyInventoryPage(
            SteamID steamid,
            int appid,
            int contextid,
            CookieContainer cookies = null,
            string startAssetid     = "",
            int count = 5000)
        {
            Logger.Log.Debug($"Loading {steamid.ConvertToUInt64()} {appid}-{contextid} inventory page");
            var url = "https://"
                      + $"steamcommunity.com/my/inventory/json/{appid}/{contextid}?l=english&count={count}&start_assetid={startAssetid}";

            var response = SteamWeb.Request(url, "GET", dataString: null, cookies: cookies, proxy: this.Proxy);
            MyInventoryRootModel inventoryRoot;

            try
            {
                inventoryRoot = JsonConvert.DeserializeObject <MyInventoryRootModel>(response);
            }
            catch (JsonException ex)
            {
                Logger.Log.Error($"Error on inventory loading - {ex.Message}", ex);
                inventoryRoot = null;
            }

            return(inventoryRoot);
        }
Ejemplo n.º 5
0
        internal bool Request(string url, NameValueCollection data, string referer,
                              string tradeOfferId, out string newTradeOfferId)
        {
            newTradeOfferId = "";
            var resp = SteamWeb.Request(url, "POST", data, _cookies, referer: referer);

            if (!string.IsNullOrEmpty(resp))
            {
                try
                {
                    var offerResponse = JsonConvert.DeserializeObject <NewTradeOfferResponse>(resp);
                    if (!string.IsNullOrEmpty(offerResponse.TradeOfferId))
                    {
                        newTradeOfferId = offerResponse.TradeOfferId;
                        return(true);
                    }

                    Error = offerResponse.TradeError;
                    Logger.Error($"Error on decline trade offer - {Error}");
                }
                catch (JsonException ex)
                {
                    Logger.Error("Error on decline trade offer", ex);
                }
            }

            return(false);
        }
Ejemplo n.º 6
0
        public bool BuyOnMarket(
            double averagePrice,
            int appid,
            string hashName,
            double?ratio,
            bool buyPackages,
            int currency)
        {
            // the ratio is a value client is ready to accept the difference between average and current price
            ratio += 1;
            var order = this.FindBuyingOrder(averagePrice, appid, hashName, ratio);
            var data  = new NameValueCollection
            {
                { "sessionid", this.SteamClient.Session.SessionID },
                { "currency", currency.ToString() },
                { "appid", appid.ToString() },
                { "market_hash_name", hashName }
            };
            var quantity = 1;

            if (buyPackages)
            {
                quantity *= order.Count;
            }

            // "G", CultureInfo.InvariantCulture - use these as arguments to convert double into string with dots
            data["price_total"] = (order.Price * 100 * quantity).ToString("G", CultureInfo.InvariantCulture);
            data["quantity"]    = quantity.ToString();
            var response = SteamWeb.Request(
                "https://steamcommunity.com/market/createbuyorder/",
                "POST",
                data,
                this.Cookies,
                proxy: this.Proxy);
            var responseJson = (NameValueCollection)JsonConvert.DeserializeObject(response);
            var success      = responseJson["success"];

            if (success == null)
            {
                Logger.Log.Error("Invalid response from createbuyorder request");
                return(false);
            }

            var buyOrderId = responseJson["buy_orderid"];

            if (success != "1")
            {
                Logger.Log.Debug(responseJson["message"]);
                if (responseJson["message"].Contains("You already have an active buy order"))
                {
                    this.CancelBuyOrder(buyOrderId);
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 7
0
        private InventoryRootModel LoadInventoryPage(SteamID steamid, int appid, int contextid,
                                                     string startAssetid = "", int count = 5000)
        {
            var url = "https://" +
                      $"steamcommunity.com/inventory/{steamid.ConvertToUInt64()}/{appid}/{contextid}?l=english&count={count}&start_assetid={startAssetid}";
            var response      = SteamWeb.Request(url, "GET", dataString: null);
            var inventoryRoot = JsonConvert.DeserializeObject <InventoryRootModel>(response);

            return(inventoryRoot);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Adds or removes the provided workshop item from the collection.
        /// </summary>
        /// <param name="workshopid">The WorkshopID of the workshopitem.</param>
        /// <param name="remove">If true the workshopitem will be removed instead of being addded.</param>
        public static void ModifyCollection(ulong workshopid, bool remove)
        {
            var             login   = Globals.SteamLogin;
            var             data    = "sessionID=" + login.Session.SessionID + "&publishedfileid=" + workshopid + "&collections%5B1377816355%5D%5B" + (remove ? "remove" : "add") + "%5D=true&collections%5B1377816355%5D%5Btitle%5D=Die+Unausstehlichen+-+TTT";
            CookieContainer cookies = new CookieContainer();

            login.Session.AddCookies(cookies);
            var response = SteamWeb.Request("https://steamcommunity.com/sharedfiles/ajaxaddtocollections", "POST", data, cookies);

            Console.WriteLine(response);
        }
Ejemplo n.º 9
0
 public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = false, string referer = "")
 {
     try
     {
         HttpWebResponse response = SteamWeb.Request(url, method, data, Cookies, ajax, referer);
         return(ReadWebStream(response));
     }
     catch (WebException we)
     {
         Debug.WriteLine(we);
         return(ReadWebStream(we.Response));
     }
 }
Ejemplo n.º 10
0
        public bool DeclineTradeOffer(ulong tradeofferid)
        {
            var options = $"?key={this._apiKey}&tradeofferid={tradeofferid}";
            var url     = string.Format(BaseUrl, "DeclineTradeOffer", "v1", options);

            var     response = SteamWeb.Request(url, "POST", data: null, proxy: this._proxy);
            dynamic json     = JsonConvert.DeserializeObject(response);

            if (json == null || json.success != "1")
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 11
0
        public static int GetGemsCount(FullRgItem item, CookieContainer steamCookies, WebProxy proxy = null)
        {
            var ownerTag = item.Description.OwnerActions?.FirstOrDefault(t => t.Name.Equals("Turn into Gems...", StringComparison.InvariantCultureIgnoreCase));

            int gemsCount = 0;

            if (ownerTag == null)
            {
                Gems.Add(item.Description.MarketHashName, gemsCount);
                return(gemsCount);
            }

            if (TryGetGemsCount(item, out gemsCount))
            {
                return(gemsCount);
            }

            //javascript:GetGooValue( '%contextid%', '%assetid%', 603770, 3, 1 )
            var regex = Regex.Match(ownerTag.Link, "javascript:GetGooValue\\( '%contextid%', '%assetid%', (\\d+), (\\d+), (\\d+) \\)");

            var appId    = regex.Groups[1].Value;
            var itemType = regex.Groups[2].Value;
            var border   = regex.Groups[3].Value;

            var response = SteamWeb.Request(
                $"https://steamcommunity.com/auction/ajaxgetgoovalueforitemtype/?appid={appId}&item_type={itemType}&border_color={border}",
                "GET",
                data: null,
                cookies: steamCookies,
                proxy: proxy);

            var json = JsonConvert.DeserializeObject <GooResponse>(response);

            if (json.Success != 1)
            {
                throw new WebException($"Success status is {json.Success}");
            }

            gemsCount = int.Parse(json.GooValue);

            Gems.Add(item.Description.MarketHashName, gemsCount);
            if (++_updateFileCounter == 5)
            {
                _updateFileCounter = 0;
                UpdateFile();
            }

            return(gemsCount);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Fetches the inventory for the given Steam ID using the Steam API.
        /// </summary>
        /// <returns>The give users inventory.</returns>
        /// <param name='steamId'>Steam identifier.</param>
        /// <param name='apiKey'>The needed Steam API key.</param>
        /// <param name="appid"></param>
        public Inventory FetchInventory(ulong steamId, string apiKey, int appid)
        {
            var attempts             = 1;
            InventoryResponse result = null;

            while ((result?.result.Items == null) && attempts <= 3)
            {
                var url =
                    $"http://api.steampowered.com/IEconItems_{appid}/GetPlayerItems/v0001/?key={apiKey}&steamid={steamId}";
                var response = SteamWeb.Request(url, "GET", data: null, referer: "http://api.steampowered.com");
                result = JsonConvert.DeserializeObject <InventoryResponse>(response);
                attempts++;
            }

            return(new Inventory(result?.result));
        }
Ejemplo n.º 13
0
        public string FetchTradeToken()
        {
            this.IsSessionUpdated = true;

            Logger.Log.Debug("Parsing trade token from - 'https://steamcommunity.com/my/tradeoffers/privacy'");

            try
            {
                var response = SteamWeb.Request(
                    "https://steamcommunity.com/my/tradeoffers/privacy",
                    "GET",
                    string.Empty,
                    this.Cookies,
                    proxy: this.Proxy);

                if (response == null)
                {
                    Logger.Log.Warn(
                        "Error on parsing trade token. Steam privacy page cant not be loaded. Try to scrap it manually from - 'https://steamcommunity.com/my/tradeoffers/privacy'");

                    return(null);
                }

                var token = Regex.Match(
                    response,
                    @"https://steamcommunity\.com/tradeoffer/new/\?partner=.+&token=(.+?)""").Groups[1].Value;

                if (string.IsNullOrEmpty(token))
                {
                    Logger.Log.Warn(
                        "Error on parsing trade token. Steam privacy page cant not be loaded. Try to scrap it manually from - 'https://steamcommunity.com/my/tradeoffers/privacy'");

                    return(null);
                }

                Logger.Log.Debug($"'{token}' trade token was successfully parsed");
                return(token);
            }
            catch (Exception e)
            {
                Logger.Log.Warn(
                    $"Error on parsing trade token. {e.Message}. Try to scrap it manually from - 'https://steamcommunity.com/my/tradeoffers/privacy'");

                return(null);
            }
        }
Ejemplo n.º 14
0
        public OfferResponse GetTradeOffer(string tradeofferid)
        {
            var options = string.Format("?key={0}&tradeofferid={1}&language={2}", this._apiKey, tradeofferid, "en_us");
            var url     = string.Format(BaseUrl, "GetTradeOffer", "v1", options);

            try
            {
                var response = SteamWeb.Request(url, "GET", data: null, proxy: this._proxy);
                var result   = JsonConvert.DeserializeObject <ApiResponse <OfferResponse> >(response);
                return(result.Response);
            }
            catch (Exception ex)
            {
                Logger.Log.Error("Error on getting trade offers", ex);
            }

            return(new OfferResponse());
        }
Ejemplo n.º 15
0
        public TradeOffersSummary GetTradeOffersSummary(uint timeLastVisit)
        {
            var options = string.Format("?key={0}&time_last_visit={1}", this._apiKey, timeLastVisit);
            var url     = string.Format(BaseUrl, "GetTradeOffersSummary", "v1", options);

            try
            {
                var response = SteamWeb.Request(url, "GET", data: null, proxy: this._proxy);
                var resp     = JsonConvert.DeserializeObject <ApiResponse <TradeOffersSummary> >(response);

                return(resp.Response);
            }
            catch (Exception ex)
            {
                Logger.Log.Error("Error on getting trade offer summary", ex);
            }

            return(new TradeOffersSummary());
        }
Ejemplo n.º 16
0
        private string FetchApiKey()
        {
            this.IsSessionUpdated = true;

            Logger.Log.Debug("Parsing steam api key from - 'https://steamcommunity.com/dev/apikey'");
            while (true)
            {
                var response = SteamWeb.Request(
                    "https://steamcommunity.com/dev/apikey",
                    "GET",
                    data: null,
                    cookies: this.Cookies,
                    proxy: this.Proxy);

                if (response != null)
                {
                    var keyParse = Regex.Match(response, @"Key: (.+)</p").Groups[1].Value.Trim();
                    if (keyParse.Length != 0)
                    {
                        Logger.Log.Debug($"{keyParse} api key was successfully parsed");
                        return(keyParse);
                    }
                }

                Logger.Log.Debug("Seems like account do not have api key. Trying to regenerate it");
                var data = new NameValueCollection
                {
                    { "domain", "domain.com" },
                    { "agreeToTerms", "agreed" },
                    { "sessionid", this.Guard.Session.SessionID },
                    { "Submit", "Register" }
                };

                SteamWeb.Request(
                    "https://steamcommunity.com/dev/registerkey",
                    "POST",
                    data: data,
                    cookies: this.Cookies,
                    proxy: this.Proxy);
            }
        }
Ejemplo n.º 17
0
        public TradeOfferAcceptResponse Accept(string tradeOfferId)
        {
            var data = new NameValueCollection
            {
                { "sessionid", this._sessionId }, { "serverid", "1" }, { "tradeofferid", tradeOfferId }
            };

            var url     = $"https://steamcommunity.com/tradeoffer/{tradeOfferId}/accept";
            var referer = $"https://steamcommunity.com/tradeoffer/{tradeOfferId}/";

            var resp = SteamWeb.Request(url, "POST", data, this._cookies, referer: referer, proxy: this._proxy);

            if (!string.IsNullOrEmpty(resp))
            {
                try
                {
                    var res = JsonConvert.DeserializeObject <TradeOfferAcceptResponse>(resp);

                    // steam can return 'null' response
                    if (res != null)
                    {
                        res.Accepted = string.IsNullOrEmpty(res.TradeError);
                        return(res);
                    }
                }
                catch (JsonException)
                {
                    return(new TradeOfferAcceptResponse {
                        TradeError = "Error parsing server response: " + resp
                    });
                }
            }

            // if it didn't work as expected, check the state, maybe it was accepted after all
            var state = this._webApi.GetOfferState(tradeOfferId);

            return(new TradeOfferAcceptResponse {
                Accepted = state == TradeOfferState.TradeOfferStateAccepted
            });
        }
Ejemplo n.º 18
0
        public bool Decline(string tradeOfferId)
        {
            var data = new NameValueCollection
            {
                { "sessionid", this._sessionId }, { "serverid", "1" }, { "tradeofferid", tradeOfferId }
            };

            var url = string.Format("https://steamcommunity.com/tradeoffer/{0}/decline", tradeOfferId);

            // should be http://steamcommunity.com/{0}/{1}/tradeoffers - id/profile persona/id64 ideally
            var referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId);

            var resp = SteamWeb.Request(url, "POST", data, this._cookies, referer: referer, proxy: this._proxy);

            if (!string.IsNullOrEmpty(resp))
            {
                try
                {
                    var json = JsonConvert.DeserializeObject <NewTradeOfferResponse>(resp);
                    if (json.TradeOfferId != null && json.TradeOfferId == tradeOfferId)
                    {
                        return(true);
                    }
                }
                catch (JsonException ex)
                {
                    Debug.WriteLine("Error on decline trade offer" + ex.Message);
                }
            }
            else
            {
                var state = this._webApi.GetOfferState(tradeOfferId);
                if (state == TradeOfferState.TradeOfferStateDeclined)
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 19
0
        public bool Cancel(string tradeOfferId)
        {
            var data = new NameValueCollection
            {
                { "sessionid", _sessionId }, { "tradeofferid", tradeOfferId }, { "serverid", "1" }
            };
            var url = string.Format("https://steamcommunity.com/tradeoffer/{0}/cancel", tradeOfferId);
            //should be http://steamcommunity.com/{0}/{1}/tradeoffers/sent/ - id/profile persona/id64 ideally
            var referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId);

            var resp = SteamWeb.Request(url, "POST", data, _cookies, referer: referer);

            if (!string.IsNullOrEmpty(resp))
            {
                try
                {
                    var json = JsonConvert.DeserializeObject <NewTradeOfferResponse>(resp);
                    if (json.TradeOfferId != null && json.TradeOfferId == tradeOfferId)
                    {
                        return(true);
                    }
                }
                catch (JsonException ex)
                {
                    Logger.Error("Error on cancel trade offer", ex);
                }
            }
            else
            {
                var state = _webApi.GetOfferState(tradeOfferId);
                if (state == TradeOfferState.TradeOfferStateCanceled)
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 20
0
        private void CancelBuyOrder(string orderid)
        {
            var data = new NameValueCollection
            {
                { "sessionid", this.SteamClient.Session.SessionID }, { "buy_orderid", orderid }
            };

            while (true)
            {
                var response = SteamWeb.Request(
                    "http://steamcommunity.com/market/cancelbuyorder/",
                    "GET",
                    data,
                    this.Cookies,
                    proxy: this.Proxy);
                var success = ((NameValueCollection)JsonConvert.DeserializeObject(response))["success"];
                if (success == "1")
                {
                    return;
                }
                Thread.Sleep(1000 * 3);
            }
        }
Ejemplo n.º 21
0
        public bool FetchTradeToken()
        {
            var response = SteamWeb.Request(
                "https://steamcommunity.com/my/tradeoffers/privacy",
                "GET",
                string.Empty,
                this.Cookies);

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

            var token = string.Empty;

            try
            {
                token = Regex.Match(response, @"https://steamcommunity\.com/tradeoffer/new/\?partner=.+&token=(.+?)""")
                        .Groups[1].Value;
            }
            catch (Exception)
            {
                // ignored
            }

            if (token != string.Empty)
            {
                var acc = SavedSteamAccount.Get().FirstOrDefault(a => a.Login == this.Guard.AccountName);
                if (acc != null)
                {
                    acc.TradeToken = token;
                    SavedSteamAccount.UpdateAll(SavedSteamAccount.Get());
                }
            }

            return(!string.IsNullOrEmpty(token));
        }
Ejemplo n.º 22
0
 public static string RetryWebRequest(SteamWeb steamWeb, string url, string method, NameValueCollection data, bool ajax = false, string referer = "")
 {
     //(_steamWeb, url, "GET", null, false, "http://steamcommunity.com");
     for (var i = 0; i < 10; i++)
     {
         try
         {
             var response = steamWeb.Request(url, method, data, ajax, referer);
             using (var responseStream = response.GetResponseStream())
             {
                 if (responseStream == null)
                 {
                     continue;
                 }
                 using (var reader = new System.IO.StreamReader(responseStream))
                 {
                     var result = reader.ReadToEnd();
                     if (string.IsNullOrEmpty(result))
                     {
                         Console.WriteLine("Web request failed (status: {0}). Retrying...", response.StatusCode);
                         Thread.Sleep(1000);
                     }
                     else
                     {
                         return(result);
                     }
                 }
             }
         }
         catch (WebException ex)
         {
             try
             {
                 using (var responseStream = ex.Response.GetResponseStream())
                 {
                     if (responseStream == null)
                     {
                         continue;
                     }
                     using (var reader = new System.IO.StreamReader(responseStream))
                     {
                         var result = reader.ReadToEnd();
                         if (!string.IsNullOrEmpty(result))
                         {
                             return(result);
                         }
                         if (ex.Status == WebExceptionStatus.ProtocolError)
                         {
                             Console.WriteLine("Status Code: {0}, {1} for {2}", (int)((HttpWebResponse)ex.Response).StatusCode, ((HttpWebResponse)ex.Response).StatusDescription, url);
                         }
                     }
                 }
             }
             catch
             {
                 // ignored
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex);
         }
     }
     return("");
 }