Improved string escaping and added it to multipart stringcontents

This commit is contained in:
ruri
2020-03-19 01:50:29 +01:00
parent e6391109c9
commit fb8b67d285
4 changed files with 39 additions and 6 deletions
+1 -1
View File
@@ -247,7 +247,7 @@ namespace RuriLib
var msg = ReplaceValues(Message, data);
byte[] b = { };
var payload = Encoding.ASCII.GetBytes(msg.Replace(@"\r\n", "\r\n"));
var payload = Encoding.ASCII.GetBytes(msg.Unescape());
// Manual implementation of the WebSocket frame
if (WebSocket)
+33
View File
@@ -29,4 +29,37 @@ namespace RuriLib
}
}
}
/// <summary>
/// Extension methods for strings.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Replaces literal values of \n, \r\n and \t with the actual escape codes.
/// </summary>
/// <param name="str">The string to unescape</param>
/// <param name="useEnvNewLine">Whether to unescape both \n and \r\n with the Environment.NewLine</param>
/// <returns>The string with unescaped escape sequences.</returns>
public static string Unescape(this string str, bool useEnvNewLine = false)
{
var stringBuilder = new StringBuilder(str)
.Replace(@"\t", "\t");
if (useEnvNewLine)
{
stringBuilder
.Replace(@"\n", Environment.NewLine)
.Replace(@"\r\n", Environment.NewLine);
}
else
{
stringBuilder
.Replace(@"\n", "\n")
.Replace(@"\r\n", "\r\n");
}
return stringBuilder.ToString();
}
}
}
+2 -2
View File
@@ -74,7 +74,7 @@ namespace RuriLib.Functions.Requests
HttpMethod method = HttpMethod.POST, bool encodeContent = false, List<LogEntry> log = null)
{
this.contentType = contentType;
var pData = Regex.Replace(postData, @"(?<!\\)\\n", Environment.NewLine).Replace(@"\\n", @"\n");
var pData = Regex.Replace(postData, @"(?<!\\)\\n", Environment.NewLine).Unescape();
if (HttpRequest.CanContainRequestBody(method))
{
@@ -136,7 +136,7 @@ namespace RuriLib.Functions.Requests
if (c.Type == MultipartContentType.String)
{
mContent.Add(new StringContent(c.Value), c.Name);
if (log != null) log.Add(new LogEntry($"Content-Disposition: form-data; name=\"{c.Name}\"{Environment.NewLine}{Environment.NewLine}{c.Value}", Colors.MediumTurquoise));
if (log != null) log.Add(new LogEntry($"Content-Disposition: form-data; name=\"{c.Name}\"{Environment.NewLine}{Environment.NewLine}{c.Value.Unescape()}", Colors.MediumTurquoise));
}
else if (c.Type == MultipartContentType.File)
{