Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Large refactor, Code Simplification #59

Merged
merged 6 commits into from
Feb 9, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ TestResults/
*.psess
*.vsp

/**/project.lock.json

# StyleCop files
StyleCop.Cache
.vs/config/applicationhost.config
Expand Down
30 changes: 11 additions & 19 deletions RedditSharp/AuthProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public AuthProvider(string clientId, string clientSecret, string redirectUri,IWe
}

/// <summary>
/// Creates the reddit OAuth2 Url to redirect the user to for authorization.
/// Creates the reddit OAuth2 Url to redirect the user to for authorization.
/// </summary>
/// <param name="state">Used to verify that the user received is the user that was sent</param>
/// <param name="scope">Determines what actions can be performed against the user.</param>
Expand All @@ -97,12 +97,9 @@ public async Task<string> GetOAuthTokenAsync(string code, bool isRefresh = false
//TODO test mono and make sure this works without security issues. Shouldn't be handled by library, should require install of cert or at least explicit calls to ingore certs
//if (Type.GetType("Mono.Runtime") != null)
// ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;

var request = _webAgent.CreatePost(AccessUrl);

var request = _webAgent.CreateRequest(AccessUrl, "POST");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(_clientId + ":" + _clientSecret)));


if (isRefresh)
{
_webAgent.WritePostBody(request, new
Expand All @@ -120,8 +117,8 @@ public async Task<string> GetOAuthTokenAsync(string code, bool isRefresh = false
redirect_uri = _redirectUri
});
}
var json = await _webAgent.ExecuteRequestAsync(request);

var json = await _webAgent.ExecuteRequestAsync(request).ConfigureAwait(false);
if (json["access_token"] != null)
{
if (json["refresh_token"] != null)
Expand All @@ -145,19 +142,17 @@ public async Task<string> GetOAuthTokenAsync(string username, string password)
// ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
//_webAgent.Cookies = new CookieContainer();

var request = _webAgent.CreatePost(AccessUrl);

var request = _webAgent.CreateRequest(AccessUrl, "POST");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(_clientId + ":" + _clientSecret)));

_webAgent.WritePostBody(request, new
{
grant_type = "password",
username,
password,
redirect_uri = _redirectUri
});
var json = await _webAgent.ExecuteRequestAsync(request);

var json = await _webAgent.ExecuteRequestAsync(request).ConfigureAwait(false);
if (json["access_token"] != null)
{
if (json["refresh_token"] != null)
Expand All @@ -177,7 +172,7 @@ public async Task<string> GetOAuthTokenAsync(string username, string password)
public async Task RevokeTokenAsync(string token, bool isRefresh)
{
string tokenType = isRefresh ? "refresh_token" : "access_token";
var request = _webAgent.CreatePost(RevokeUrl);
var request = _webAgent.CreateRequest(RevokeUrl, "POST");

request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(_clientId + ":" + _clientSecret)));

Expand All @@ -186,10 +181,7 @@ public async Task RevokeTokenAsync(string token, bool isRefresh)
token = token,
token_type = tokenType
});


var data = await _webAgent.ExecuteRequestAsync(request);

await _webAgent.ExecuteRequestAsync(request).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -200,13 +192,13 @@ public async Task RevokeTokenAsync(string token, bool isRefresh)
[Obsolete("Reddit.InitOrUpdateUser is preferred")]
public async Task<AuthenticatedUser> GetUserAsync(string accessToken)
{
var request = _webAgent.CreateGet(OauthGetMeUrl);
var request = _webAgent.CreateRequest(OauthGetMeUrl, "GET");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken);
var response = await _webAgent.GetResponseAsync(request);
var result = await response.Content.ReadAsStringAsync();
var thingjson = "{\"kind\": \"t2\", \"data\": " + result + "}";
var json = JObject.Parse(thingjson);
return new AuthenticatedUser().Init(new Reddit(), json, _webAgent);
return new AuthenticatedUser(new Reddit(_webAgent), json);
}
}
}
4 changes: 2 additions & 2 deletions RedditSharp/BotWebAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public BotWebAgent(string username, string password, string clientID, string cli
/// <inheritdoc/>
public override HttpRequestMessage CreateRequest(string url, string method)
{
//add 5 minutes for clock skew to ensure requests succeed
//add 5 minutes for clock skew to ensure requests succeed
if (url != AuthProvider.AccessUrl && DateTime.UtcNow.AddMinutes(5) > TokenValidTo)
{
Task.Run(GetNewTokenAsync).Wait();
Expand All @@ -63,7 +63,7 @@ protected override HttpRequestMessage CreateRequest(Uri uri, string method)

private async Task GetNewTokenAsync()
{
AccessToken = await TokenProvider.GetOAuthTokenAsync(Username, Password);
AccessToken = await TokenProvider.GetOAuthTokenAsync(Username, Password).ConfigureAwait(false);
TokenValidTo = DateTime.UtcNow.AddHours(1);
}
}
Expand Down
2 changes: 1 addition & 1 deletion RedditSharp/Data/LinkData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ internal class LinkData : SubmitData
/// </summary>
[RedditAPIName("extension")]
internal string Extension { get; set; }

/// <summary>
/// Url of the link.
/// </summary>
Expand Down
47 changes: 9 additions & 38 deletions RedditSharp/Domain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,13 @@

namespace RedditSharp
{
public class Domain
public class Domain : RedditObject
{
private const string DomainPostUrl = "/domain/{0}.json";
private const string DomainNewUrl = "/domain/{0}/new.json?sort=new";
private const string DomainHotUrl = "/domain/{0}/hot.json";
private string DomainPostUrl => $"/domain/{Name}.json";
private string DomainNewUrl => $"/domain/{Name}/new.json?sort=new";
private string DomainHotUrl => $"/domain/{Name}/hot.json";
private const string FrontPageUrl = "/.json";

[JsonIgnore]
private Reddit Reddit { get; set; }

[JsonIgnore]
private IWebAgent WebAgent { get; set; }

/// <summary>
/// Domain name
/// </summary>
Expand All @@ -26,48 +20,25 @@ public class Domain
/// <summary>
/// Get a <see cref="Listing{T}"/> of posts made for this domain.
/// </summary>
public Listing<Post> Posts
{
get
{
return new Listing<Post>(Reddit, string.Format(DomainPostUrl, Name), WebAgent);
}
}
public Listing<Post> Posts => new Listing<Post>(Reddit, DomainPostUrl);

/// <summary>
/// Get a <see cref="Listing{T}"/> of posts made for this domain that are in the new queue.
/// </summary>
public Listing<Post> New
{
get
{
return new Listing<Post>(Reddit, string.Format(DomainNewUrl, Name), WebAgent);
}
}
public Listing<Post> New => new Listing<Post>(Reddit, DomainNewUrl);

/// <summary>
/// Get a <see cref="Listing{T}"/> of posts made for this domain that are in the hot queue.
/// </summary>
public Listing<Post> Hot
{
get
{
return new Listing<Post>(Reddit, string.Format(DomainHotUrl, Name), WebAgent);
}
}
public Listing<Post> Hot => new Listing<Post>(Reddit, DomainHotUrl);

protected internal Domain(Reddit reddit, Uri domain, IWebAgent webAgent)
protected internal Domain(Reddit reddit, Uri domain) : base(reddit)
{
Reddit = reddit;
WebAgent = webAgent;
Name = domain.Host;
}

/// <inheritdoc/>
public override string ToString()
{
return "/domain/" + Name;
}
public override string ToString() => "/domain/" + Name;
}
}

12 changes: 6 additions & 6 deletions RedditSharp/Flairs/FlairTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,31 @@ public enum FlairPosition
/// Flair text.
/// </summary>
[JsonProperty("flair_text")]
public string Text { get; set; }
public string Text { get; }

/// <summary>
/// Flair clss class.
/// </summary>
[JsonProperty("flair_css_class")]
public string CssClass { get; set; }
public string CssClass { get; }

/// <summary>
/// Flair template id.
/// </summary>
[JsonProperty("flair_template_id")]
public string TemplateId { get; set; }
public string TemplateId { get; }

/// <summary>
/// Set to true if this is user editable.
/// </summary>
[JsonProperty("flair_text_editable")]
public bool IsEditable { get; set; }
public bool IsEditable { get; }

/// <summary>
/// Position of the flair left or right.
/// </summary>
[JsonProperty("flair_position")]
[JsonConverter(typeof(StringEnumConverter))]
public FlairPosition FlairPosition { get; set; }
public FlairPosition FlairPosition { get; }
}
}
}
6 changes: 3 additions & 3 deletions RedditSharp/Interfaces/IWebAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ namespace RedditSharp
public interface IWebAgent
{
string AccessToken { get; set; }
Task<JToken> Get(string url);
Task<JToken> Post(string url, object data, params string[] additionalFields);
Task<JToken> Put(string url, object data);
HttpRequestMessage CreateRequest(string url, string method);
HttpRequestMessage CreateGet(string url);
HttpRequestMessage CreatePost(string url);
Task<JToken> ExecuteRequestAsync(HttpRequestMessage request);
Task<JToken> CreateAndExecuteRequestAsync(string url);
Task<HttpResponseMessage> GetResponseAsync(HttpRequestMessage request);
void WritePostBody(HttpRequestMessage request, object data, params string[] additionalFields);
}
Expand Down
Loading