|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Net; |
| 5 | +using System.Text; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace RedditSharp |
| 9 | +{ |
| 10 | + public class BotWebAgent : WebAgent |
| 11 | + { |
| 12 | + //private so it doesn't leak app secret to other code |
| 13 | + private AuthProvider TokenProvider; |
| 14 | + private string Username; |
| 15 | + private string Password; |
| 16 | + |
| 17 | + public DateTime TokenValidTo { get; set; } |
| 18 | + |
| 19 | + public BotWebAgent(string username, string password, string clientID, string clientSecret, string redirectURI) |
| 20 | + { |
| 21 | + Username = username; |
| 22 | + Password = password; |
| 23 | + EnableRateLimit = true; |
| 24 | + RateLimit = RateLimitMode.Burst; |
| 25 | + RootDomain = "oauth.reddit.com"; |
| 26 | + TokenProvider = new AuthProvider(clientID, clientSecret, redirectURI, this); |
| 27 | + GetNewToken(); |
| 28 | + } |
| 29 | + |
| 30 | + public override HttpWebRequest CreateRequest(string url, string method) |
| 31 | + { |
| 32 | + //add 5 minutes for clock skew to ensure requests succeed |
| 33 | + if (url != AuthProvider.AccessUrl && DateTime.UtcNow.AddMinutes(5) > TokenValidTo) |
| 34 | + { |
| 35 | + GetNewToken(); |
| 36 | + } |
| 37 | + return base.CreateRequest(url, method); |
| 38 | + } |
| 39 | + |
| 40 | + protected override HttpWebRequest CreateRequest(Uri uri, string method) |
| 41 | + { |
| 42 | + //add 5 minutes for clock skew to ensure requests succeed |
| 43 | + if (uri.ToString() != AuthProvider.AccessUrl && DateTime.UtcNow.AddMinutes(5) > TokenValidTo) |
| 44 | + { |
| 45 | + GetNewToken(); |
| 46 | + } |
| 47 | + return base.CreateRequest(uri, method); |
| 48 | + } |
| 49 | + |
| 50 | + private void GetNewToken() |
| 51 | + { |
| 52 | + AccessToken = TokenProvider.GetOAuthToken(Username, Password); |
| 53 | + TokenValidTo = DateTime.UtcNow.AddHours(1); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | +} |
0 commit comments