private async Task GetUpdatedLimits(string token, string tokenSecret) { RateLimitCache.Get[TwitterAPIEndpoint.RateLimitStatus].ResetIfNeeded(); UserRateLimitInfo userInfo = GetCurrentUserInfo(rateLimitDb, TwitterAPIEndpoint.RateLimitStatus, userManager, User); string appResponseBody = await TwitterAPIUtils.GetResponse( configuration, AuthenticationType.Application, TwitterAPIEndpoint.RateLimitStatus, TwitterAPIUtils.RateLimitStatusQuery(RateLimitResources), null, null, null); string userResponseBody = (token == null || tokenSecret == null) ? null : await TwitterAPIUtils.GetResponse( configuration, AuthenticationType.User, TwitterAPIEndpoint.RateLimitStatus, TwitterAPIUtils.RateLimitStatusQuery(RateLimitResources), token, tokenSecret, userInfo); var appResults = (appResponseBody != null) ? RateLimitResults.FromJson(appResponseBody) : null; var userResults = (userResponseBody != null) ? RateLimitResults.FromJson(userResponseBody) : null; UpdateEndpointLimits(appResults, userResults); }
private void UpdateEndpointLimits(RateLimitResults appResults, RateLimitResults userResults) { foreach (var endpoint in Enum.GetValues(typeof(TwitterAPIEndpoint)).Cast <TwitterAPIEndpoint>()) { string key = ""; switch (endpoint) { case TwitterAPIEndpoint.RateLimitStatus: continue; case TwitterAPIEndpoint.SearchTweets: key = "/search/tweets"; break; case TwitterAPIEndpoint.UsersShow: key = "/users/show/:id"; break; case TwitterAPIEndpoint.UsersLookup: key = "/users/lookup"; break; case TwitterAPIEndpoint.OAuthAuthorize: key = "/oauth/authorize"; break; case TwitterAPIEndpoint.FriendsIDs: key = "/friends/following/ids"; break; case TwitterAPIEndpoint.FollowersIDs: key = "/followers/ids"; break; default: throw new Exception("Unimplemented TwitterAPIEndpoint"); } RateLimitCache.Get[endpoint].Update(ParseLimit(appResults, key)); var userInfo = GetCurrentUserInfo(rateLimitDb, endpoint, userManager, User); if (userInfo != null) { userInfo.Update(ParseLimit(userResults, key)); rateLimitDb.Update(userInfo); rateLimitDb.SaveChanges(); } else { var user = new UserRateLimitInfo() { Type = endpoint }; user.Update(ParseLimit(userResults, key)); rateLimitDb.Add(user); rateLimitDb.SaveChanges(); } } }
private static int ParseLimit(RateLimitResults results, string key) { string resourceName = key.Substring(1, key.IndexOf('/', 1) - 1); return((int)(results?.Resources.GetValueOrDefault(resourceName)?.GetValueOrDefault(key)?.Remaining ?? 0)); }