Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
Overv committed Jan 27, 2012
0 parents commit 4f2a9c7
Show file tree
Hide file tree
Showing 5 changed files with 341 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Discard binaries

obj/
bin/
36 changes: 36 additions & 0 deletions Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "SteamAPI" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "SteamAPI" )]
[assembly: AssemblyCopyright( "Copyright © 2012" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid( "8678fb2c-d7d6-42d3-8011-6190f0463716" )]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "1.0.0.0" )]
[assembly: AssemblyFileVersion( "1.0.0.0" )]
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Library for C# giving access to the functionality of the Steam Web API.
243 changes: 243 additions & 0 deletions SteamAPISession.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace SteamWebAPI
{
/// <summary>
/// Class allowing you to use the Steam Web API to log in and use Steam Friends functionality.
/// </summary>
///
public class SteamAPISession
{
private String accessToken;
private String umqid;
private String steamId;
private int message = 0;

/// <summary>
/// Enumeration of possible authentication results.
/// </summary>
public enum LoginStatus
{
LoginFailed,
LoginSuccessful,
SteamGuard
}

/// <summary>
/// Structure containing basic friend info.
/// </summary>
public class Friend
{
public String steamid;
public bool blocked;
public DateTime friendSince;
}

/// <summary>
/// Structure containing server info.
/// </summary>
public class ServerInfo
{
public DateTime serverTime;
public String serverTimeString;
}

/// <summary>
/// Authenticate with a username and password.
/// Sends the SteamGuard e-mail if it has been set up.
/// </summary>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="emailauthcode">SteamGuard code sent by e-mail</param>
/// <returns>Indication of the authentication status.</returns>
public LoginStatus Authenticate( String username, String password, String emailauthcode = "" )
{
HttpWebResponse response = steamRequest( "ISteamOAuth2/GetTokenWithCredentials/v0001",
"client_id=DE45CD61&grant_type=password&username=" + Uri.EscapeDataString( username ) + "&password=" + Uri.EscapeDataString( password ) + "&x_emailauthcode=" + emailauthcode + "&scope=read_profile%20write_profile%20read_client%20write_client" );

if ( response != null && (int)response.StatusCode == 200 )
{
JObject data = JObject.Parse( new StreamReader( response.GetResponseStream() ).ReadToEnd() );

if ( data["access_token"] != null )
{
accessToken = (String)data["access_token"];

return login() ? LoginStatus.LoginSuccessful : LoginStatus.LoginFailed;
}
else if ( ( (string)data["x_errorcode"] ).Equals( "steamguard_code_required" ) )
return LoginStatus.SteamGuard;
else
return LoginStatus.LoginFailed;
}
else
{
return LoginStatus.LoginFailed;
}
}

/// <summary>
/// Authenticate with an access token previously retrieved with a username
/// and password (and SteamGuard code).
/// </summary>
/// <param name="accessToken">Access token retrieved with credentials</param>
/// <returns>Indication of the authentication status.</returns>
public LoginStatus Authenticate( String accessToken )
{
this.accessToken = accessToken;
return login() ? LoginStatus.LoginSuccessful : LoginStatus.LoginFailed;
}

/// <summary>
/// Fetch all friends for a given user.
/// </summary>
/// <remarks>This function does not provide detailed information.</remarks>
/// <param name="steamId">SteamID of target user or self</param>
/// <returns>List of friends or null on failure.</returns>
public List<Friend> GetFriends( String steamId = null )
{
if ( umqid == null ) return null;
if ( steamId == null ) steamId = this.steamId;

HttpWebResponse response = steamRequest( "ISteamUserOAuth/GetFriendList/v0001?access_token=" + accessToken + "&steamid=" + steamId );

if ( response != null && (int)response.StatusCode == 200 )
{
JObject data = JObject.Parse( new StreamReader( response.GetResponseStream() ).ReadToEnd() );

if ( data["friends"] != null )
{
List<Friend> friends = new List<Friend>();

foreach ( JObject friend in data["friends"] )
{
Friend f = new Friend();
f.steamid = (String)friend["steamid"];
f.blocked = ( (String)friend["relationship"] ).Equals( "ignored" );
f.friendSince = unixTimestamp( (long)friend["friend_since"] );
friends.Add( f );
}

return friends;
}
else
{
return null;
}
}
else
{
return null;
}
}

public ServerInfo GetServerInfo()
{
HttpWebResponse response = steamRequest( "ISteamWebAPIUtil/GetServerInfo/v0001" );

if ( response != null && (int)response.StatusCode == 200 )
{
JObject data = JObject.Parse( new StreamReader( response.GetResponseStream() ).ReadToEnd() );

if ( data["servertime"] != null )
{
ServerInfo info = new ServerInfo();
info.serverTime = unixTimestamp( (long)data["servertime"] );
info.serverTimeString = (String)data["servertimestring"];
return info;
}
else
{
return null;
}
}
else
{
return null;
}
}

/// <summary>
/// Helper function to complete the login procedure and check the
/// credentials.
/// </summary>
/// <returns>Whether the login was successful or not.</returns>
private bool login()
{
HttpWebResponse response = steamRequest( "ISteamWebUserPresenceOAuth/Logon/v0001",
"?access_token=" + accessToken );

if ( response != null && (int)response.StatusCode == 200 )
{
JObject data = JObject.Parse( new StreamReader( response.GetResponseStream() ).ReadToEnd() );

if ( data["umqid"] != null )
{
steamId = (String)data["steamid"];
umqid = (String)data["umqid"];
message = (int)data["message"];
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}

/// <summary>
/// Helper function to perform Steam API requests.
/// </summary>
/// <param name="get">Path URI</param>
/// <param name="post">Post data</param>
/// <returns>Web response info</returns>
private HttpWebResponse steamRequest( String get, String post = null )
{
System.Net.ServicePointManager.Expect100Continue = false;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "https://63.228.223.110/" + get );
request.Host = "api.steampowered.com:443";
request.ProtocolVersion = HttpVersion.Version11;

if ( post != null )
{
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes( post );

request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;

Stream requestStream = request.GetRequestStream();
requestStream.Write( postBytes, 0, postBytes.Length );
requestStream.Close();

message++;
}

try
{
return (HttpWebResponse)request.GetResponse();

This comment has been minimized.

Copy link
@bladecoding

bladecoding Jan 27, 2012

You need to Dispose the HttpWebResponse. msdn "You must call the Close method to close the stream and release the connection. Failure to do so may cause your application to run out of connections". So if you don't dispose it eventually you wont be able to make anymore requests.
Also You shouldn't really be returning the HttpWebResponse. Instead just return the data.

}
catch ( WebException e )
{
return null;
}
}

private DateTime unixTimestamp( long timestamp )
{
DateTime origin = new DateTime( 1970, 1, 1, 0, 0, 0, 0 );
return origin.AddSeconds( timestamp );
}
}
}
57 changes: 57 additions & 0 deletions SteamWebAPI.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D846D108-D95B-4488-BA01-E487DA220C17}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SteamAPI</RootNamespace>
<AssemblyName>SteamAPI</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\..\Libraries\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SteamAPISession.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

0 comments on commit 4f2a9c7

Please sign in to comment.