diff --git a/RestAPI.cs b/RestAPI.cs index 6d04d19..285abad 100644 --- a/RestAPI.cs +++ b/RestAPI.cs @@ -9,6 +9,7 @@ using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; using WooCommerceNET.Base; @@ -164,9 +165,16 @@ public virtual async Task SendHttpClientRequest(string endpoint, Requ if (JWTRequestFilter != null) JWTRequestFilter.Invoke(request); - var buffer = Encoding.UTF8.GetBytes($"username={wc_key}&password={wc_secret}"); + var convKey = ConvertAmpersandsToUTF8Hex(wc_key); + var convSecret = ConvertAmpersandsToUTF8Hex(wc_secret); + + var buffer = Encoding.UTF8.GetBytes($"username={convKey}&password={convSecret}"); Stream dataStream = await request.GetRequestStreamAsync().ConfigureAwait(false); dataStream.Write(buffer, 0, buffer.Length); + dataStream.Close(); + + request.ContentLength = buffer.Length; + WebResponse response = await request.GetResponseAsync().ConfigureAwait(false); Stream resStream = response.GetResponseStream(); string result = await GetStreamContent(resStream, "UTF-8").ConfigureAwait(false); @@ -233,7 +241,12 @@ public virtual async Task SendHttpClientRequest(string endpoint, Requ httpWebRequest.ContentType = "application/x-www-form-urlencoded"; Stream dataStream = await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false); - FileStream fileStream = new FileStream(parms["path"], FileMode.Open, FileAccess.Read); + + // If the given path is a physical path, open file. If not, read from URL. + var fileStream = parms["source"] == "local" ? + new FileStream(parms["path"], FileMode.Open, FileAccess.Read) : + (new WebClient()).OpenRead(parms["path"]); + byte[] buffer = new byte[4096]; int bytesRead = 0; @@ -451,6 +464,12 @@ public string DateTimeFormat return IsLegacy ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:ss"; } } + + private string ConvertAmpersandsToUTF8Hex(string original) + { + var pattern = new Regex("[&]"); + return pattern.Replace(original, "%26"); + } } public class WP_JWT_Object diff --git a/WordPress/v2/WPObject.cs b/WordPress/v2/WPObject.cs index e2d1caa..0e0dbe8 100644 --- a/WordPress/v2/WPObject.cs +++ b/WordPress/v2/WPObject.cs @@ -73,11 +73,12 @@ public WPMediaItem(RestAPI api) : base(api) API = api; } - public async Task Add(string fileName, string filePath) + public async Task Add(string fileName, string filePath, bool fromUrl = false) { Dictionary ps = new Dictionary(); ps.Add("name", fileName); ps.Add("path", filePath); + ps.Add("source", fromUrl ? "url" : "local"); return API.DeserializeJSon(await API.PostRestful(APIEndpoint, "fileupload", ps).ConfigureAwait(false)); }