private List <Achievements> GetSchemaForGame(int AppId, List <Achievements> AllAchievements) { try { using (dynamic steamWebAPI = WebAPI.GetInterface("ISteamUserStats", SteamApiKey)) { KeyValue SchemaForGame = steamWebAPI.GetSchemaForGame(appid: AppId, l: LocalLang); foreach (KeyValue AchievementsData in SchemaForGame.Children.Find(x => x.Name == "availableGameStats").Children.Find(x => x.Name == "achievements").Children) { AllAchievements.Find(x => x.ApiName == AchievementsData.Name).IsHidden = AchievementsData.Children.Find(x => x.Name == "hidden").Value == "1"; AllAchievements.Find(x => x.ApiName == AchievementsData.Name).UrlUnlocked = AchievementsData.Children.Find(x => x.Name == "icon").Value; AllAchievements.Find(x => x.ApiName == AchievementsData.Name).UrlLocked = AchievementsData.Children.Find(x => x.Name == "icongray").Value; if (AllAchievements.Find(x => x.ApiName == AchievementsData.Name).IsHidden) { AllAchievements.Find(x => x.ApiName == AchievementsData.Name).Description = FindHiddenDescription(AppId, AllAchievements.Find(x => x.ApiName == AchievementsData.Name).Name); } } } } catch (Exception ex) { Common.LogError(ex, "SuccessStory", $"Error on GetPlayerAchievements({SteamId}, {AppId}, {LocalLang})"); } return(AllAchievements); }
internal void DeclineTradeOffer(ulong tradeID) { if ((tradeID == 0) || string.IsNullOrEmpty(Bot.BotConfig.SteamApiKey)) { Logging.LogNullError(nameof(tradeID) + " || " + nameof(Bot.BotConfig.SteamApiKey), Bot.BotName); return; } KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxRetries) && (response == null); i++) { using (dynamic iEconService = WebAPI.GetInterface("IEconService", Bot.BotConfig.SteamApiKey)) { iEconService.Timeout = Timeout; try { response = iEconService.DeclineTradeOffer( tradeofferid: tradeID.ToString(), method: WebRequestMethods.Http.Post, secure: !Program.GlobalConfig.ForceHttp ); } catch (Exception e) { Logging.LogGenericException(e, Bot.BotName); } } } if (response == null) { Logging.LogGenericWarning("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName); } }
public BanInfo GetBanInfoFor(SteamID steamID) { try { using (dynamic steamUser = WebAPI.GetInterface("ISteamUser", WebAPIKeyResolver.APIKey)) { KeyValue pair = steamUser.GetPlayerBans(steamids: steamID.ConvertToUInt64()); foreach (var get in pair["players"].Children) { if (get["SteamId"].AsUnsignedLong() == steamID.ConvertToUInt64()) { return(new BanInfo { SteamID = get["SteamId"].AsUnsignedLong(), CommunityBanned = get["CommunityBanned"].AsBoolean(), VacBanned = get["VACBanned"].AsBoolean(), VacBanCount = get["NumberOfVACBans"].AsInteger(), DaysSinceLastBan = get["DaysSinceLastBan"].AsInteger(), GameBanCount = get["NumberOfGameBans"].AsInteger(), EconomyBan = get["EconomyBan"].AsString() }); } } } } catch (WebException ex) { _log.Error(ex, "A error occured when trying to get the Ban Information for {SteamID}.", steamID.ConvertToUInt64()); } _log.Warning("Did not receive ban informations for {SteamID}. Skipping...", steamID.ConvertToUInt64()); return(null); }
internal bool DeclineTradeOffer(ulong tradeID) { if (ApiKey == null) { return(false); } if (tradeID == 0) { return(false); } KeyValue response; using (dynamic iEconService = WebAPI.GetInterface("IEconService")) { // Timeout iEconService.Timeout = Timeout; try { response = iEconService.DeclineTradeOffer( key: ApiKey, tradeofferid: tradeID.ToString(), method: WebRequestMethods.Http.Post, secure: true ); } catch (Exception e) { Logging.LogGenericException(Bot.BotName, e); return(false); } } return(response != null); // Steam API doesn't respond with any error code, assume any response is a success }
private static bool AuthenticateUser() { // 32 byte random blob of data var sessionKey = CryptoHelper.GenerateRandomBlock(32); byte[] encryptedSessionKey; // ... which is then encrypted with RSA using the Steam system's public key using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Steam.Instance.Client.Universe))) { encryptedSessionKey = rsa.Encrypt(sessionKey); } // users hashed loginkey, AES encrypted with the sessionkey var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(Encoding.ASCII.GetBytes(WebAPIUserNonce), sessionKey); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { KeyValue result; try { result = userAuth.AuthenticateUser( steamid: Steam.Instance.Client.SteamID.ConvertToUInt64(), sessionkey: WebHelpers.UrlEncode(encryptedSessionKey), encrypted_loginkey: WebHelpers.UrlEncode(encryptedLoginKey), method: "POST", secure: true ); } catch (WebException e) { var response = (HttpWebResponse)e.Response; if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) { IsAuthorized = false; if (Steam.Instance.Client.IsConnected) { Steam.Instance.User.RequestWebAPIUserNonce(); } } Log.WriteWarn("WebAuth", "Failed to authenticate: {0}", e.Message); return(false); } Cookies = new CookieContainer(); Cookies.Add(new Cookie("steamLogin", result["token"].AsString(), "/", "store.steampowered.com")); Cookies.Add(new Cookie("steamLoginSecure", result["tokensecure"].AsString(), "/", "store.steampowered.com")); } IsAuthorized = true; Log.WriteInfo("WebAuth", "Authenticated"); return(true); }
public ActionResult <UserGPs> GetUserGamesById(string id) { UserGPs ugps = new UserGPs(); ugps.gamePlaytimes = new HashSet <GamePlaytime>(); using (dynamic steam = WebAPI.GetInterface("IPlayerService", Environment.GetEnvironmentVariable("STEAM_API_KEY"))) { // note the usage of c#'s dynamic feature, which can be used // to make the api a breeze to use try { string user_id = GetSteamID(id); KeyValue res = steam.GetOwnedGames(steamid: user_id); // check if we can get games; maybe profile is private or bad id if (res.Children.Find(kv => kv.Name == "games") == null) { // same as returning null return(NoContent()); } ugps.user = GetSteamProfile(user_id); // get hashset of known games to compare to HashSet <Game> games; // use the cached games to save on time games = new HashSet <Game>(_gameCacheService.Get(), new GameEqualityComparer()); foreach (KeyValue game in res["games"].Children) { uint appid = game["appid"].AsUnsignedInteger(); Game g = new Game(); g.name = "unknown"; g.appid = appid; g.store_link = Game.STORE_GAME_LINK_PREFIX + appid; g.header_image = Game.STEAM_LOGO_URL; // since it's stored in minutes double playtime = game["playtime_forever"].AsUnsignedInteger() / 60.0; if (games.TryGetValue(g, out Game f)) { ugps.gamePlaytimes.Add(new GamePlaytime(f, playtime)); } else { ugps.gamePlaytimes.Add(new GamePlaytime(g, playtime)); } } } catch (Exception e) { _logger.LogError(e, "Failed to get owned games"); return(NotFound()); } } return(ugps); }
internal bool DeclineTradeOffer(ulong tradeID) { if (tradeID == 0 || ApiKey == null) { return(false); } KeyValue response = null; using (dynamic iEconService = WebAPI.GetInterface("IEconService", ApiKey)) { iEconService.Timeout = Timeout; for (byte i = 0; i < WebBrowser.MaxRetries && response == null; i++) { try { response = iEconService.DeclineTradeOffer( tradeofferid: tradeID.ToString(), method: WebRequestMethods.Http.Post, 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(false); } return(true); }
private static EResult ResolveVanityURL(string input, EVanityURLType urlType, out SteamID steamID) { steamID = new SteamID(); using (dynamic steamUser = WebAPI.GetInterface("ISteamUser", Settings.Current.Steam.WebAPIKey)) { steamUser.Timeout = (int)TimeSpan.FromSeconds(5).TotalMilliseconds; KeyValue response; try { response = steamUser.ResolveVanityURL(vanityurl: input, url_type: (int)urlType); } catch (WebException) { return(EResult.Timeout); } var eResult = (EResult)response["success"].AsInteger(); if (eResult == EResult.OK) { steamID.SetFromUInt64((ulong)response["steamid"].AsLong()); } return(eResult); } }
internal uint GetServerTime() { KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxRetries) && (response == null); i++) { using (dynamic iTwoFactorService = WebAPI.GetInterface("ITwoFactorService")) { iTwoFactorService.Timeout = Timeout; try { response = iTwoFactorService.QueryTime( method: WebRequestMethods.Http.Post, secure: !Program.GlobalConfig.ForceHttp ); } catch (Exception e) { Logging.LogGenericException(e, Bot.BotName); } } } if (response != null) { return(response["server_time"].AsUnsignedInteger()); } Logging.LogGenericWarning("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName); return(0); }
public void GetNews(Action <List <KeyValue> > callback) { using (dynamic steamNews = WebAPI.GetInterface("ISteamNews")) { try { KeyValue kvNews = steamNews.GetNewsForApp(appid: 322330); callback(kvNews["newsitems"]["newsitem"].Children); } catch (System.Net.Http.HttpRequestException e) { if (e.HResult == -2146233079)//hex will cause some problems........ { //this HResult means invalid SSL cert var ProcessList = System.Diagnostics.Process.GetProcesses(); foreach (System.Diagnostics.Process P in ProcessList) { if (P.ProcessName == "steamcommunity_302.caddy") { //中国特色 //no necessary of I18N, only steam users in china use this Logger.Warn("Steamcommunity302证书出错"); UI.Dialog.Open("获取新闻失败,请到steamcommunity302重新生成代理证书!" , "警告", UI.Dialog.Buttons.OK); return; } } Logger.Warn("Invalid steam SSL Cert."); } else { //do nothing. } } } }
public BanInfo GetBanInfoFor(SteamID steamId) { using(dynamic steamUser = WebAPI.GetInterface("ISteamUser", APIKey)) { KeyValue pair = steamUser.GetPlayerBans(steamids: steamId.ConvertToUInt64()); foreach(var get in pair["players"].Children) { if(get["SteamId"].AsUnsignedLong() == steamId.ConvertToUInt64()) { return new BanInfo { SteamId = get["SteamId"].AsUnsignedLong(), CommunityBanned = get["CommunityBanned"].AsBoolean(), VacBanned = get["VACBanned"].AsBoolean(), VacBanCount = get["NumberOfVACBans"].AsInteger(), DaysSinceLastBan = get["DaysSinceLastBan"].AsInteger(), GameBanCount = get["NumberOfGameBans"].AsInteger(), EconomyBan = get["EconomyBan"].AsString() }; } } } _log.Warning("Did not receive ban informations for {SteamID}. Skipping..."); return null; }
public bool RequestSteamUserInfo(string vanityURL, out ulong steamID64) { try { using (dynamic steamUser = WebAPI.GetInterface("ISteamUser", _keyManager.SWAKey)) { KeyValue pair = steamUser.ResolveVanityURL(vanityurl: vanityURL); if (pair["success"].AsInteger() == 1) { steamID64 = pair["steamid"].AsUnsignedLong(); return(true); } Log.Error("Could not resolve custom URL {URL} to SteamID64: {Error}", vanityURL, pair["message"].AsString()); } } catch (WebException ex) { Log.Error("Could not resolve custom URL {URL} to SteamID64: {Error}", vanityURL, ex.Message); } steamID64 = 0; return(false); }
public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = String.Empty; SessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // userAuth.Timeout = TimeSpan.FromSeconds(5); // Generate an AES session key. var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // AES encrypt the loginkey with our session key. byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; // Get the Authentification Result. try { Dictionary <string, object> sessionArgs = new Dictionary <string, object>() { { "steamid", client.SteamID.ConvertToUInt64() }, { "sessionkey", cryptedSessionKey }, { "encrypted_loginkey", cryptedLoginKey } }; authResult = userAuth.Call(HttpMethod.Post, "AuthenticateUser", args: sessionArgs); } catch (Exception hehe) { Console.WriteLine("Unable to make AuthenticateUser API Request: {0}", hehe.Message); Token = TokenSecure = null; return(false); } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); // Adding cookies to the cookie container. _cookies.Add(new Cookie("sessionid", SessionID, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("Steam_Language", "english", string.Empty, SteamCommunityDomain)); Console.WriteLine("Crukies: " + VerifyCookies()); return(true); } }
protected override void OnRun() { Parallel.ForEach(Settings.Current.ImportantApps, app => { uint lastVersion = 0; bool hasLastVersion = versionMap.TryGetValue(app.AppID, out lastVersion); using (dynamic steamApps = WebAPI.GetInterface("ISteamApps")) { steamApps.Timeout = TimeSpan.FromSeconds(30); KeyValue results = null; try { results = steamApps.UpToDateCheck(appid: app.AppID, version: lastVersion); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.Timeout) { // log everything but timeouts Log.WriteWarn("UpToDateJob", "Unable to make UpToDateCheck request: {0}", ex.Message); } return; } catch (TimeoutException) { // no need to log timeouts return; } if (!results["success"].AsBoolean()) { return; // no useful result from the api, or app isn't configured } uint requiredVersion = ( uint )results["required_version"].AsInteger(-1); if (( int )requiredVersion == -1) { return; // some apps are incorrectly configured and don't report a required version } if (!results["up_to_date"].AsBoolean()) { // update our cache of required version versionMap[app.AppID] = requiredVersion; if (hasLastVersion) { // if we previously cached the version, display that it changed IRC.Instance.SendToTag("game-updates", "{0} (version: {1}) is no longer up to date. New version: {2}", Steam.Instance.GetAppName(app.AppID), lastVersion, requiredVersion); } } } }); }
///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> /// <param name="myUniqueId">Id what you get to login.</param> /// <param name="client">An instance of a SteamClient.</param> /// <param name="myLoginKey">Login Key of your account.</param> /// <returns>A bool, which is true if the login was successful.</returns> public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = ""; SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // Generate an AES session key. var 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(client.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // AES encrypt the loginkey with our session key. byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; // Get the Authentification Result. try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception e) { Token = TokenSecure = null; return(false); } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); // Adding cookies to the cookie container. _cookies.Add(new Cookie("sessionid", SessionId, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("Steam_Language", "english", string.Empty, SteamCommunityDomain)); return(true); } }
public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { mToken = mTokenSecure = ""; mSessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); mCookieContainer = new CookieContainer(); using (var userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; try { var dict = new System.Collections.Generic.Dictionary <string, object>() { { "steamid", client.SteamID.ConvertToUInt64() }, { "sessionkey", cryptedSessionKey }, { "encrypted_loginkey", cryptedLoginKey }, { "secure", true } }; authResult = userAuth.Call(System.Net.Http.HttpMethod.Post, "AuthenticateUser", 1, dict); } catch (Exception) { mToken = mTokenSecure = null; return(false); } mToken = authResult["token"].AsString(); mTokenSecure = authResult["tokensecure"].AsString(); mCookieContainer.Add(new Cookie("sessionid", mSessionId, string.Empty, mSteamCommunityDomain)); mCookieContainer.Add(new Cookie("steamLogin", mToken, string.Empty, mSteamCommunityDomain)); mCookieContainer.Add(new Cookie("steamLoginSecure", mTokenSecure, string.Empty, mSteamCommunityDomain)); return(true); } }
public override void OnRun() { uint lastVersion = 0; if (hasLastVersion) { lastVersion = this.version; } using (dynamic steamApps = WebAPI.GetInterface("ISteamApps")) { steamApps.Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; KeyValue results = null; try { results = steamApps.UpToDateCheck(appid: appid, version: lastVersion); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.Timeout) { //Log.WriteWarn("UpToDateJob", "Unable to make UpToDateCheck request: {0}", ex.Message); } return; } if (!results["success"].AsBoolean()) { return; // no useful result from the api, or app isn't configured } uint requiredVersion = (uint)results["required_version"].AsInteger(-1); if ((int)requiredVersion == -1) { return; // some apps are incorrectly configured and don't report a required version } if (!results["up_to_date"].AsBoolean()) { if (this.hasLastVersion) { // if we previously cached the version, display that it changed Program.Instance.Log(new LogMessage(LogSeverity.Info, "UpdateCheck", string.Format("{0} (version: {1}) is no longer up to date. New version: {2}", Helpers.GetAppName(appid), lastVersion, requiredVersion))); Helpers.SendMessageAllToGenerals(string.Format("{0} (version: {1}) is no longer up to date. New version: {2} \nLearn more: {3}", Helpers.GetAppName(appid), lastVersion, requiredVersion, ("https://steamdb.info/patchnotes/?appid=" + appid))); } // update our cache of required version this.version = requiredVersion; this.hasLastVersion = true; } } }
static void News() { using (dynamic steamNews = WebAPI.GetInterface("ISteamNews")) { KeyValue kvNews = steamNews.GetNewsForApp(appid: 730); foreach (KeyValue news in kvNews["newsitems"]["newsitem"].Children) { Console.WriteLine("News: {0}", news["title"].AsString()); } } }
internal Dictionary <uint, string> GetOwnedGames(ulong steamID) { if ((steamID == 0) || string.IsNullOrEmpty(Bot.BotConfig.SteamApiKey)) { // TODO: Correct this when Mono 4.4+ will be a latest stable one | https://bugzilla.xamarin.com/show_bug.cgi?id=39455 Logging.LogNullError("steamID || SteamApiKey", Bot.BotName); //Logging.LogNullError(nameof(steamID) + " || " + nameof(Bot.BotConfig.SteamApiKey), Bot.BotName); return(null); } KeyValue response = null; using (dynamic iPlayerService = WebAPI.GetInterface("IPlayerService", Bot.BotConfig.SteamApiKey)) { iPlayerService.Timeout = Timeout; for (byte i = 0; (i < WebBrowser.MaxRetries) && (response == null); i++) { try { response = iPlayerService.GetOwnedGames( steamid: steamID, include_appinfo: 1, secure: !Program.GlobalConfig.ForceHttp ); } catch (Exception e) { Logging.LogGenericException(e, Bot.BotName); } } } if (response == null) { Logging.LogGenericWTF("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName); return(null); } Dictionary <uint, string> result = new Dictionary <uint, string>(response["games"].Children.Count); foreach (KeyValue game in response["games"].Children) { uint appID = (uint)game["appid"].AsUnsignedLong(); if (appID == 0) { Logging.LogNullError(nameof(appID)); continue; } result[appID] = game["name"].Value; } return(result); }
internal Dictionary <uint, string> GetOwnedGames(ulong steamID) { if ((steamID == 0) || string.IsNullOrEmpty(Bot.BotConfig.SteamApiKey)) { Logging.LogNullError(nameof(steamID) + " || " + nameof(Bot.BotConfig.SteamApiKey), Bot.BotName); return(null); } KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxRetries) && (response == null); i++) { using (dynamic iPlayerService = WebAPI.GetInterface("IPlayerService", Bot.BotConfig.SteamApiKey)) { iPlayerService.Timeout = Timeout; try { response = iPlayerService.GetOwnedGames( steamid: steamID, include_appinfo: 1, secure: !Program.GlobalConfig.ForceHttp ); } catch (Exception e) { Logging.LogGenericException(e, Bot.BotName); } } } if (response == null) { Logging.LogGenericWarning("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName); return(null); } Dictionary <uint, string> result = new Dictionary <uint, string>(response["games"].Children.Count); foreach (KeyValue game in response["games"].Children) { uint appID = game["appid"].AsUnsignedInteger(); if (appID == 0) { Logging.LogNullError(nameof(appID), Bot.BotName); return(null); } result[appID] = game["name"].Value; } return(result); }
///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> public static bool Authenticate(string myUniqueId, SteamClient client, out string sessionId, out string token, out string tokensecure, string myLoginKey) { sessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception) { token = null; tokensecure = null; return(false); } token = authResult ["token"].AsString(); tokensecure = authResult["tokensecure"].AsString(); return(true); } }
private Tuple <List <Achievements>, List <GameStats> > GetSchemaForGame(int AppId, List <Achievements> AllAchievements, List <GameStats> AllStats) { try { using (dynamic steamWebAPI = WebAPI.GetInterface("ISteamUserStats", SteamApiKey)) { KeyValue SchemaForGame = steamWebAPI.GetSchemaForGame(appid: AppId, l: LocalLang); foreach (KeyValue AchievementsData in SchemaForGame.Children.Find(x => x.Name == "availableGameStats").Children.Find(x => x.Name == "achievements").Children) { AllAchievements.Find(x => x.ApiName == AchievementsData.Name).IsHidden = AchievementsData.Children.Find(x => x.Name == "hidden").Value == "1"; AllAchievements.Find(x => x.ApiName == AchievementsData.Name).UrlUnlocked = AchievementsData.Children.Find(x => x.Name == "icon").Value; AllAchievements.Find(x => x.ApiName == AchievementsData.Name).UrlLocked = AchievementsData.Children.Find(x => x.Name == "icongray").Value; if (AllAchievements.Find(x => x.ApiName == AchievementsData.Name).IsHidden) { AllAchievements.Find(x => x.ApiName == AchievementsData.Name).Description = FindHiddenDescription(AppId, AllAchievements.Find(x => x.ApiName == AchievementsData.Name).Name); } } var ListStatsData = SchemaForGame.Children.Find(x => x.Name == "availableGameStats").Children.Find(x => x.Name == "stats").Children; foreach (KeyValue StatsData in ListStatsData) { if (AllStats.Find(x => x.Name == StatsData.Name) == null) { double.TryParse(StatsData.Children.Find(x => x.Name == "defaultvalue").Value, out double ValueStats); AllStats.Add(new GameStats { Name = StatsData.Name, DisplayName = StatsData.Children.Find(x => x.Name == "displayName").Value, Value = ValueStats }); } else { AllStats.Find(x => x.Name == StatsData.Name).DisplayName = StatsData.Children.Find(x => x.Name == "displayName").Value; } } } } catch (Exception ex) { Common.LogError(ex, "SuccessStory", $"Error on GetPlayerAchievements({SteamId}, {AppId}, {LocalLang})"); } return(Tuple.Create(AllAchievements, AllStats)); }
/// <summary> /// Get the tradeoffersSummary, so we have an overview of all our tradeoffers /// </summary> /// <returns></returns> public KeyValue GetTradeOffersSummaryInterface() { using (dynamic IEconService = WebAPI.GetInterface(IEconServiceInterface, m_steamWeb.APIKey)) { try { return(IEconService.GetTradeOffersSummary( secure: true)); } catch (Exception e) { m_logger.Warning(e.Message); throw; } } }
private static User GetSteamProfile(string id) { using (dynamic steam = WebAPI.GetInterface("ISteamUser", Environment.GetEnvironmentVariable("STEAM_API_KEY"))) { KeyValue res = steam.GetPlayerSummaries(steamids: id); if (res["players"] != null) { User user = new User(); user.user_id = id; user.personaname = res["players"]["player"].Children[0]["personaname"].AsString(); user.IconURL = res["players"]["player"].Children[0]["avatarfull"].AsString(); return(user); } } return(null); }
/// <summary>Gets a complete list of all applications (not-DLC) from Steam.</summary> /// <returns>Collection of steam titles: id, name</returns> protected static Dictionary <int, string> GetSteamAppList() { Dictionary <int, string> t = new Dictionary <int, string>(); using (dynamic conn = WebAPI.GetInterface("ISteamApps")) { KeyValue response = conn.GetAppList2(); List <KeyValue> z = response["apps"].Children; foreach (var item in z) { t.Add(item["appid"].AsInteger(), item["name"].AsString()); } } return(t); }
public bool RequestBanInfo(SteamID steamID, out BanInfo banInfo) { if (steamID != null && !string.IsNullOrEmpty(_keyManager.SWAKey)) { try { using (dynamic steamUser = WebAPI.GetInterface("ISteamUser", _keyManager.SWAKey)) { KeyValue pair = steamUser.GetPlayerBans(steamids: steamID.ConvertToUInt64()); foreach (var get in pair["players"].Children) { if (get["SteamId"].AsUnsignedLong() == steamID.ConvertToUInt64()) { banInfo = new BanInfo { SteamID = get["SteamId"].AsUnsignedLong(), CommunityBanned = get["CommunityBanned"].AsBoolean(), VacBanned = get["VACBanned"].AsBoolean(), VacBanCount = get["NumberOfVACBans"].AsInteger(), DaysSinceLastBan = get["DaysSinceLastBan"].AsInteger(), GameBanCount = get["NumberOfGameBans"].AsInteger(), EconomyBan = get["EconomyBan"].AsString() }; return(true); } } } } catch (WebException ex) { Log.Error(ex, "A error occured when trying to get the Ban Information for {SteamID}.", steamID.ConvertToUInt64()); } Log.Warning("Did not receive ban informations for {SteamID}. Skipping...", steamID.ConvertToUInt64()); banInfo = null; return(false); } Log.Warning("No valid Web API key has been found. Skipping ban checking..."); banInfo = null; return(false); }
/// <summary> /// Get one tradeoffer with the passed tradeOfferID /// </summary> /// <param name="_tradeOfferID"></param> /// <returns></returns> public KeyValue GetTradeOfferInterface(int _tradeOfferID) { using (dynamic IEconService = WebAPI.GetInterface(IEconServiceInterface, m_steamWeb.APIKey)) { // ALWAYS TRY to work with interfaces, because it could go wrong and destroy everything try { return(IEconService.GetTradeOffer( tradeofferid: _tradeOfferID, secure: true)); } catch (Exception e) { m_logger.Warning(e.Message); throw; } } }
/// <summary> /// Cancel a sent tradeoffer /// </summary> /// <param name="_tradeOfferID"></param> /// <returns></returns> public KeyValue CancelTradeOfferInterface(int _tradeOfferID) { using (dynamic IEconService = WebAPI.GetInterface(IEconServiceInterface, m_steamWeb.APIKey)) { try { return(IEconService.CancelTradeOffer( tradeofferid: _tradeOfferID, method: WebRequestMethods.Http.Post, secure: true)); } catch (Exception e) { m_logger.Warning(e.Message); throw; } } }
// Used for checking if Steam Web API key is valid public bool RequestAPIMethods() { try { using (dynamic steamWebAPIUtil = WebAPI.GetInterface("ISteamWebAPIUtil", _keyManager.SWAKey)) { KeyValue pair = steamWebAPIUtil.GetSupportedAPIList0001(); return(true); } } catch (Exception ex) { Log.Error(ex.Message); } return(false); }
public static bool ResolveVanityURL(string customUrl, out SteamID steamId) { steamId = new SteamID(); if (string.IsNullOrWhiteSpace(customUrl)) { return(false); } var apiKey = Settings.Current.WebAPIKey; if (apiKey == null) { Log.WriteWarn("SteamUtils", "Unable to use ResolveVanityURL: no web api key in settings"); return(false); } using (dynamic iface = WebAPI.GetInterface("ISteamUser", apiKey)) { iface.Timeout = ( int )TimeSpan.FromSeconds(30).TotalMilliseconds; KeyValue results = null; try { results = iface.ResolveVanityURL(vanityurl: customUrl); } catch (WebException) { return(false); } EResult eResult = ( EResult )results["success"].AsInteger(); if (eResult == EResult.OK) { steamId = ( ulong )results["steamid"].AsLong(); return(true); } } return(false); }