Skip to content

Commit

Permalink
Refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
openbullet committed Dec 15, 2024
1 parent 993d7b4 commit 85bec99
Show file tree
Hide file tree
Showing 4 changed files with 289 additions and 249 deletions.
134 changes: 72 additions & 62 deletions RuriLib/Functions/Http/HttpClientRequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,9 @@ public async override Task HttpRequestMultipart(BotData data, MultipartHttpReque
// Rewrite the value of the Content-Type header otherwise it will add double quotes around it like
// Content-Type: multipart/form-data; boundary="------WebKitFormBoundaryewozmkbxwbblilpm"
var multipartContent = new MultipartFormDataContent(options.Boundary);
multipartContent.Headers.ContentType.Parameters.First(o => o.Name == "boundary").Value = options.Boundary;
multipartContent.Headers.ContentType!.Parameters.First(o => o.Name == "boundary").Value = options.Boundary;

FileStream fileStream = null;
FileStream? fileStream = null;

foreach (var c in options.Contents)
{
Expand Down Expand Up @@ -219,13 +219,11 @@ public async override Task HttpRequestMultipart(BotData data, MultipartHttpReque
}
}

using var request = new HttpRequestMessage
{
Method = new System.Net.Http.HttpMethod(options.Method.ToString()),
RequestUri = new Uri(options.Url),
Version = Version.Parse(options.HttpVersion),
Content = multipartContent
};
using var request = new HttpRequestMessage();
request.Method = new System.Net.Http.HttpMethod(options.Method.ToString());
request.RequestUri = new Uri(options.Url);
request.Version = Version.Parse(options.HttpVersion);
request.Content = multipartContent;

foreach (var header in options.CustomHeaders)
{
Expand All @@ -248,20 +246,23 @@ public async override Task HttpRequestMultipart(BotData data, MultipartHttpReque
}
finally
{
if (fileStream != null)
if (fileStream is not null)
{
await fileStream.DisposeAsync().ConfigureAwait(false);
}
}
}

private static void LogHttpRequestData(BotData data, HttpRequestMessage request, string content = null, string boundary = null)
private static void LogHttpRequestData(BotData data, HttpRequestMessage request,
string? content = null, string? boundary = null)
{
using var writer = new StringWriter();

// Log the method, uri and http version
writer.WriteLine($"{request.Method.Method} {request.RequestUri.PathAndQuery} HTTP/{request.Version.Major}.{request.Version.Minor}");
writer.WriteLine($"{request.Method.Method} {request.RequestUri?.PathAndQuery} HTTP/{request.Version.Major}.{request.Version.Minor}");

// Log the headers
writer.WriteLine($"Host: {request.RequestUri.Host}");
writer.WriteLine($"Host: {request.RequestUri?.Host}");

foreach (var header in request.Headers)
{
Expand All @@ -270,10 +271,12 @@ private static void LogHttpRequestData(BotData data, HttpRequestMessage request,
}

// Log the cookie header
var cookies = data.COOKIES.Select(c => $"{c.Key}={c.Value}");
var cookies = data.COOKIES.Select(c => $"{c.Key}={c.Value}").ToList();

if (cookies.Any())
if (cookies.Count != 0)
{
writer.WriteLine($"Cookie: {string.Join("; ", cookies)}");
}

if (request.Content != null && content != null)
{
Expand All @@ -293,9 +296,9 @@ private static void LogHttpRequestData(BotData data, HttpRequestMessage request,
writer.WriteLine(content);
break;

case MultipartFormDataContent x:
case MultipartFormDataContent:
writer.WriteLine($"Content-Type: multipart/form-data; boundary=\"{boundary}\"");
writer.WriteLine($"Content-Length: (not calculated)");
writer.WriteLine("Content-Length: (not calculated)");
writer.WriteLine();
writer.WriteLine(content);
break;
Expand Down Expand Up @@ -327,20 +330,13 @@ private static async Task LogHttpResponseData(BotData data, HttpResponseMessage
}

// Address
data.ADDRESS = response.RequestMessage.RequestUri.AbsoluteUri;
data.ADDRESS = response.RequestMessage!.RequestUri!.AbsoluteUri;
data.Logger.Log($"Address: {data.ADDRESS}", LogColors.DodgerBlue);

// Response code
data.RESPONSECODE = (int)response.StatusCode;
data.Logger.Log($"Response code: {data.RESPONSECODE}", LogColors.Citrine);

// Headers
static string GetHeaderValue(KeyValuePair<string, IEnumerable<string>> header)
{
var separator = commaHeaders.Contains(header.Key) ? ", " : " ";
return string.Join(separator, header.Value);
}

data.HEADERS = response.Headers.ToDictionary(h => h.Key, GetHeaderValue);

foreach (var header in response.Content.Headers)
Expand All @@ -362,39 +358,6 @@ static string GetHeaderValue(KeyValuePair<string, IEnumerable<string>> header)
data.COOKIES[cookie.Name] = cookie.Value;
}

static bool TryParseCookie(string cookieHeader, out string cookieName, out string cookieValue)
{
cookieName = null;
cookieValue = null;

if (cookieHeader.Length == 0)
{
return false;
}

var endCookiePos = cookieHeader.IndexOf(';');
var separatorPos = cookieHeader.IndexOf('=');

if (separatorPos == -1)
{
// Invalid cookie, simply don't add it
return false;
}

cookieName = cookieHeader[..separatorPos];

if (endCookiePos == -1)
{
cookieValue = cookieHeader[(separatorPos + 1)..];
}
else
{
cookieValue = cookieHeader.Substring(separatorPos + 1, (endCookiePos - separatorPos) - 1);
}

return true;
}

// HttpClient has trouble with the Set-Cookie header https://github.com/dotnet/runtime/issues/20942
// so we will help it out...
foreach (var header in response.Headers)
Expand All @@ -406,7 +369,10 @@ static bool TryParseCookie(string cookieHeader, out string cookieName, out strin
{
if (TryParseCookie(cookieHeader, out var cookieName, out var cookieValue))
{
data.COOKIES[cookieName] = cookieValue;
if (cookieName is not null && cookieValue is not null)
{
data.COOKIES[cookieName] = cookieValue;
}
}
}
}
Expand All @@ -416,7 +382,7 @@ static bool TryParseCookie(string cookieHeader, out string cookieName, out strin
data.Logger.Log(data.COOKIES.Select(h => $"{h.Key}: {h.Value}"), LogColors.Khaki);

// Decode brotli if still compressed
if (data.HEADERS.ContainsKey("Content-Encoding") && data.HEADERS["Content-Encoding"].Contains("br"))
if (data.HEADERS.TryGetValue("Content-Encoding", out var value) && value.Contains("br"))
{
try
{
Expand Down Expand Up @@ -448,8 +414,16 @@ static bool TryParseCookie(string cookieHeader, out string cookieName, out strin
// Source
if (!string.IsNullOrWhiteSpace(requestOptions.CodePagesEncoding))
{
data.SOURCE = CodePagesEncodingProvider.Instance
.GetEncoding(requestOptions.CodePagesEncoding).GetString(data.RAWSOURCE);
var encoding = CodePagesEncodingProvider.Instance
.GetEncoding(requestOptions.CodePagesEncoding);

if (encoding is null)
{
throw new NotSupportedException(
$"Encoding {requestOptions.CodePagesEncoding} is not supported");
}

data.SOURCE = encoding.GetString(data.RAWSOURCE);
}
else
{
Expand All @@ -463,6 +437,42 @@ static bool TryParseCookie(string cookieHeader, out string cookieName, out strin

data.Logger.Log("Received Payload:", LogColors.ForestGreen);
data.Logger.Log(data.SOURCE, LogColors.GreenYellow, true);
return;

static bool TryParseCookie(string cookieHeader, out string? cookieName, out string? cookieValue)
{
cookieName = null;
cookieValue = null;

if (cookieHeader.Length == 0)
{
return false;
}

var endCookiePos = cookieHeader.IndexOf(';');
var separatorPos = cookieHeader.IndexOf('=');

if (separatorPos == -1)
{
// Invalid cookie, simply don't add it
return false;
}

cookieName = cookieHeader[..separatorPos];

cookieValue = endCookiePos == -1 ?
cookieHeader[(separatorPos + 1)..]
: cookieHeader.Substring(separatorPos + 1, endCookiePos - separatorPos - 1);

return true;
}

// Headers
static string GetHeaderValue(KeyValuePair<string, IEnumerable<string>> header)
{
var separator = commaHeaders.Contains(header.Key) ? ", " : " ";
return string.Join(separator, header.Value);
}
}
}
}
Loading

0 comments on commit 85bec99

Please sign in to comment.