PluralKit/Myriad/Rest/Ratelimit/RatelimitHeaders.cs

51 lines
2.0 KiB
C#
Raw Normal View History

2020-12-22 12:15:26 +00:00
using System;
using System.Linq;
using System.Net.Http;
namespace Myriad.Rest.Ratelimit
{
public record RatelimitHeaders
{
public RatelimitHeaders() { }
public RatelimitHeaders(HttpResponseMessage response)
{
ServerDate = response.Headers.Date;
if (response.Headers.TryGetValues("X-RateLimit-Limit", out var limit))
2021-02-08 15:30:18 +00:00
if (int.TryParse(limit.First(), out var limitNum))
Limit = limitNum;
2020-12-22 12:15:26 +00:00
if (response.Headers.TryGetValues("X-RateLimit-Remaining", out var remaining))
2021-02-08 15:30:18 +00:00
if (int.TryParse(remaining!.First(), out var remainingNum))
Remaining = remainingNum;
2020-12-22 12:15:26 +00:00
if (response.Headers.TryGetValues("X-RateLimit-Reset", out var reset))
2021-02-08 15:30:18 +00:00
if (double.TryParse(reset!.First(), out var resetNum))
Reset = DateTimeOffset.FromUnixTimeMilliseconds((long) (resetNum * 1000));
2020-12-22 12:15:26 +00:00
if (response.Headers.TryGetValues("X-RateLimit-Reset-After", out var resetAfter))
2021-02-08 15:30:18 +00:00
if (double.TryParse(resetAfter!.First(), out var resetAfterNum))
ResetAfter = TimeSpan.FromSeconds(resetAfterNum);
2020-12-22 12:15:26 +00:00
if (response.Headers.TryGetValues("X-RateLimit-Bucket", out var bucket))
Bucket = bucket.First();
if (response.Headers.TryGetValues("X-RateLimit-Global", out var global))
2021-02-08 15:30:18 +00:00
if (bool.TryParse(global!.First(), out var globalBool))
Global = globalBool;
2020-12-22 12:15:26 +00:00
}
public bool Global { get; init; }
public int? Limit { get; init; }
public int? Remaining { get; init; }
public DateTimeOffset? Reset { get; init; }
public TimeSpan? ResetAfter { get; init; }
public string? Bucket { get; init; }
public DateTimeOffset? ServerDate { get; init; }
public bool HasRatelimitInfo =>
Limit != null && Remaining != null && Reset != null && ResetAfter != null && Bucket != null;
}
}