diff --git a/Imagekit.UnitTests/ClientImagekitTests.cs b/Imagekit.UnitTests/ClientImagekitTests.cs index 9f6f789..6c5257f 100644 --- a/Imagekit.UnitTests/ClientImagekitTests.cs +++ b/Imagekit.UnitTests/ClientImagekitTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; @@ -69,6 +70,16 @@ public void Constructor_TransformationPosition(string transformationPosition, bo } } + [Fact] + public void Upload_Exception() + { + var fileName = Guid.NewGuid().ToString(); + var auth = TestHelpers.AuthParamResponseFaker.Generate(); + var imagekit = new ClientImagekit(GOOD_PUBLICKEY, GOOD_URLENDPOINT); + var ex = Assert.ThrowsAsync(async () => await imagekit.UploadAsync("", auth)); + Assert.Equal(Util.errorMessages.MISSING_UPLOAD_FILE_PARAMETER, ex.Result.Message); + } + [Fact] public void Upload() { @@ -91,6 +102,29 @@ public void Upload() Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response)); } + [Fact] + public void UploadBytes() + { + var fileName = Guid.NewGuid().ToString(); + string base64 = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; + byte[] bytes = Convert.FromBase64String(base64); + var auth = TestHelpers.AuthParamResponseFaker.Generate(); + var responseObj = TestHelpers.ImagekitResponseFaker.Generate(); + var httpResponse = new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(JsonConvert.SerializeObject(responseObj)) + }; + var httpClient = TestHelpers.GetTestHttpClient(httpResponse, + TestHelpers.GetUploadRequestMessageValidator(base64, fileName, publicKey: GOOD_PUBLICKEY, clientAuth: auth)); + Util.Utils.SetHttpClient(httpClient); + + var imagekit = new ClientImagekit(GOOD_PUBLICKEY, GOOD_URLENDPOINT) + .FileName(fileName); + var response = imagekit.Upload(bytes, auth); + Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response)); + } + [Fact] public async Task UploadAsync() { diff --git a/Imagekit.UnitTests/ServerImagekitTests.cs b/Imagekit.UnitTests/ServerImagekitTests.cs index c333cfd..d841430 100644 --- a/Imagekit.UnitTests/ServerImagekitTests.cs +++ b/Imagekit.UnitTests/ServerImagekitTests.cs @@ -142,6 +142,27 @@ public void GetUploadData_TagsString() Assert.Equal("tag1,tag2", actualTags); } + [Fact] + public void GetUploadData_Generic() + { + var fileName = Guid.NewGuid().ToString(); + var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) + .FileName(fileName) + .Folder("/test/") + .isPrivateFile(true) + .UseUniqueFileName(false) + .CustomCoordinates("10,10,100,100") + .ResponseFields("tags,customCoordinates,isPrivateFile") + .Tags("tag1,tag2"); + var data = imagekit.getUploadData(); + Assert.True(data.TryGetValue("responseFields", out string respFields), "ResponseFields upload data not found"); + Assert.True(data.TryGetValue("useUniqueFileName", out string uniqueParam), "UseUniqueFileName upload not found"); + Assert.True(data.TryGetValue("folder", out string folder), "folder upload not found"); + Assert.Equal("tags,customCoordinates,isPrivateFile", respFields); + Assert.Equal("false", uniqueParam); + Assert.Equal("/test/", folder); + } + [Fact] public void GetUploadData_TagsArray() { @@ -154,6 +175,51 @@ public void GetUploadData_TagsArray() Assert.Equal("tag1,tag2", actualTags); } + [Fact] + public void GetUploadData_MissingFileName_Exception() + { + var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) + .Tags("tag1"); + var ex = Assert.Throws(() => imagekit.getUploadData()); + Assert.Equal(errorMessages.MISSING_UPLOAD_FILENAME_PARAMETER, ex.Message); + } + + [Fact] + public void ListFiles() + { + var fileId = Guid.NewGuid().ToString(); + var responseObj = TestHelpers.ListAPIResponseFaker.Generate(); + var httpResponse = new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(JsonConvert.SerializeObject(responseObj)) + }; + var httpClient = TestHelpers.GetTestHttpClient(httpResponse); + Util.Utils.SetHttpClient(httpClient); + + var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT); + var response = imagekit.ListFiles(); + Assert.Equal(responseObj.StatusCode, response[0].StatusCode); + } + + [Fact] + public async void DeleteApi_Response() + { + var fileId = Guid.NewGuid().ToString(); + var responseObj = TestHelpers.DeleteAPIResponseFaker.Generate(); + var httpResponse = new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(JsonConvert.SerializeObject(responseObj)) + }; + var httpClient = TestHelpers.GetTestHttpClient(httpResponse); + Util.Utils.SetHttpClient(httpClient); + + var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT); + var response = await imagekit.DeleteFileAsync(fileId); + Assert.Equal(responseObj.StatusCode, response.StatusCode); + } + [Theory] [InlineData(null)] [InlineData("null")] @@ -256,6 +322,19 @@ public void IsLocalPathTest(string path, bool expected) Assert.Equal(expected, Util.Utils.IsLocalPath(path)); } + [Theory] + [InlineData("https://example.com/test.jpg", true)] + [InlineData("http://example.com/", true)] + [InlineData("ftp://example.com", false)] + [InlineData(@"C:\test\test 1.jpg", false)] + [InlineData(@"C:\test\test.jpg", false)] + [InlineData(@"\\test.com\test.jpg", false)] + [InlineData("http:\\mysite\test.xml", false)] + public void IsValidURITest(string url, bool expected) + { + Assert.Equal(expected, Util.Utils.IsValidURI(url)); + } + [Fact] public void Url_WithoutUrl_Source() { @@ -288,6 +367,22 @@ public void Url_Signed() Assert.Equal("https://ik.imagekit.io/test_url_endpoint/default-image.jpg?ik-s=d0f5c0d0c92c0072068b45d3d5a73ab6e306dbf8", imageURL); } + [Fact] + public void Url_Signed_Timestamp() + { + string imageURL = imagekit.Url(new Transformation()).Path(SAMPLE_PATH).Signed(true).ExpireSeconds(300).Generate(); + Assert.Contains("https://ik.imagekit.io/test_url_endpoint/default-image.jpg?ik-t=", imageURL); + } + + [Fact] + public void Url_Signed_Without_priavteKey() + { + ClientImagekit imagekit1 = new ClientImagekit(GOOD_PUBLICKEY, URLENDPOINT) + .Path(SAMPLE_PATH).Signed(true).ExpireSeconds(300); + var ex = Assert.Throws(() => imagekit1.Url(new Transformation()).Path(SAMPLE_PATH).Signed(true).ExpireSeconds(300).Generate()); + Assert.Equal(errorMessages.PRIVATE_KEY_MISSING, ex.ParamName); + } + [Fact] public void Url_WithPath_Transformation() { @@ -302,6 +397,13 @@ public void Url_WithSRC_Transform() Assert.Equal(URLENDPOINT + "/default-image.jpg?tr=h-300%2Cw-400", imageURL); } + [Fact] + public void Url_WithSRC_Param_Transform() + { + string imageURL = imagekit.Url(new Transformation().Height(300).Width(400)).Src(SAMPLE_SRC_URL+"?a=test").Generate(); + Assert.Equal(URLENDPOINT + "/default-image.jpg?a=test&tr=h-300%2Cw-400", imageURL); + } + [Fact] public void Url_WithPath_Multiple_LeadingSlash() { diff --git a/Imagekit.UnitTests/TestHelpers.cs b/Imagekit.UnitTests/TestHelpers.cs index b6f3148..ea93674 100644 --- a/Imagekit.UnitTests/TestHelpers.cs +++ b/Imagekit.UnitTests/TestHelpers.cs @@ -51,6 +51,13 @@ static TestHelpers() .RuleFor(u => u.expire, (f, u) => DateTimeOffset.UtcNow.AddMinutes(30).ToUnixTimeSeconds().ToString()) .RuleFor(u => u.signature, (f, u) => f.Random.Utf16String()); + public static Faker DeleteAPIResponseFaker = new Faker() + .RuleFor(u => u.Exception, (f, u) => f.Random.Bool()) + .RuleFor(u => u.StatusCode, (f, u) => 200) + .RuleFor(u => u.Message, (f, u) => f.Random.Utf16String()) + .RuleFor(u => u.Help, (f, u) => f.Random.Utf16String()) + .RuleFor(u => u.XIkRequestId, (f, u) => null); + public static Faker MetadataResponseFaker = new Faker() .RuleFor(u => u.Exif, (f, u) => f.Random.Utf16String()) .RuleFor(u => u.Density, (f, u) => f.Random.Int()) diff --git a/Imagekit/Imagekit.cs b/Imagekit/Imagekit.cs index 85ec589..c3ac5e8 100644 --- a/Imagekit/Imagekit.cs +++ b/Imagekit/Imagekit.cs @@ -139,7 +139,18 @@ public async Task> ListFilesAsync() Uri apiEndpoint = new Uri(Utils.GetFileApi() + "?" + string.Join("&", param)); var response = await Utils.GetAsync(apiEndpoint, (string)options["privateKey"]).ConfigureAwait(false); var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JsonConvert.DeserializeObject>(responseContent); + try + { + return JsonConvert.DeserializeObject>(responseContent); + } catch + { + ListAPIResponse resp = JsonConvert.DeserializeObject(responseContent); + resp.StatusCode = (int)response.StatusCode; + resp.XIkRequestId = response.Headers.FirstOrDefault(x => x.Key == "x-ik-requestid").Value?.First(); + List respList=new List(); + respList.Add(resp); + return respList; + } } diff --git a/Imagekit/Url.cs b/Imagekit/Url.cs index dd99b80..f2ca831 100644 --- a/Imagekit/Url.cs +++ b/Imagekit/Url.cs @@ -157,11 +157,14 @@ public bool AddAsQueryParameter() public string GetSignature(string url, string expiryTimestamp) { var endPoint = RemoveTrailingSlash((string)options["urlEndpoint"]); - if (string.IsNullOrEmpty((string)options["privateKey"]) || string.IsNullOrEmpty((string)options["urlEndpoint"])) + string str = Regex.Replace(url, endPoint + "/", "") + expiryTimestamp; + try + { + var privateKey = (string)options["privateKey"]; + } catch { throw new ArgumentNullException(errorMessages.PRIVATE_KEY_MISSING); } - string str = Regex.Replace(url, endPoint + "/", "") + expiryTimestamp; return Utils.calculateSignature(str, Encoding.ASCII.GetBytes((string)options["privateKey"])); } } diff --git a/Imagekit/Util/Utils.cs b/Imagekit/Util/Utils.cs index 2b8abe4..2252b30 100644 --- a/Imagekit/Util/Utils.cs +++ b/Imagekit/Util/Utils.cs @@ -226,15 +226,15 @@ public static HttpResponseMessage PostUpload(Uri uri, Dictionary public static bool IsLocalPath(string p) { - if (p.StartsWith("http:\\", StringComparison.Ordinal)) + if (p.StartsWith("http:", StringComparison.Ordinal)) { return false; } - else if (p.StartsWith("https:\\", StringComparison.Ordinal)) + else if (p.StartsWith("https:", StringComparison.Ordinal)) { return false; } - else if (p.StartsWith("ftp:\\", StringComparison.Ordinal)) + else if (p.StartsWith("ftp:", StringComparison.Ordinal)) { return false; }