diff --git a/CloudinaryDotNet.IntegrationTests/IntegrationTestBase.cs b/CloudinaryDotNet.IntegrationTests/IntegrationTestBase.cs index 992afd38..4b82efee 100644 --- a/CloudinaryDotNet.IntegrationTests/IntegrationTestBase.cs +++ b/CloudinaryDotNet.IntegrationTests/IntegrationTestBase.cs @@ -85,6 +85,8 @@ public partial class IntegrationTestBase protected Account m_account; protected Cloudinary m_cloudinary; + internal CloudinaryUpload m_cloudinaryUpload; + internal CloudinaryAdmin m_cloudinaryAdmin; protected Dictionary> m_publicIdsToClear; protected List m_transformationsToClear; @@ -108,6 +110,8 @@ public virtual void Initialize() m_account = GetAccountInstance(); m_cloudinary = GetCloudinaryInstance(m_account); + m_cloudinaryAdmin = GetCloudinaryAdminInstance(m_account); + m_cloudinaryUpload = GetCloudinaryUploadInstance(m_account); SaveTestResources(assembly); @@ -358,6 +362,34 @@ private Account GetAccountInstance() return account; } + /// + /// A convenient method for initialization of new Cloudinary Admin instance with necessary checks + /// + /// Instance of Account + /// New Cloudinary Admin instance + internal CloudinaryAdmin GetCloudinaryAdminInstance(Account account) + { + var cloudinaryAdmin = new CloudinaryAdmin(account); + if(!string.IsNullOrWhiteSpace(m_apiBaseAddress)) + cloudinaryAdmin.Api.ApiBaseAddress = m_apiBaseAddress; + + return cloudinaryAdmin; + } + + /// + /// A convenient method for initialization of new Cloudinary Upload instance with necessary checks + /// + /// Instance of Account + /// New Cloudinary Upload instance + internal CloudinaryUpload GetCloudinaryUploadInstance(Account account) + { + var cloudinaryUpload = new CloudinaryUpload(account); + if(!string.IsNullOrWhiteSpace(m_apiBaseAddress)) + cloudinaryUpload.Api.ApiBaseAddress = m_apiBaseAddress; + + return cloudinaryUpload; + } + /// /// A convenient method for initialization of new Cloudinary instance with necessary checks /// @@ -365,10 +397,7 @@ private Account GetAccountInstance() /// New Cloudinary instance protected Cloudinary GetCloudinaryInstance(Account account) { - Cloudinary cloudinary = new Cloudinary(account); - if(!string.IsNullOrWhiteSpace(m_apiBaseAddress)) - cloudinary.Api.ApiBaseAddress = m_apiBaseAddress; - + var cloudinary = new Cloudinary(account); return cloudinary; } diff --git a/CloudinaryDotNet.IntegrationTests/UploadApi/MultiMethodsTest.cs b/CloudinaryDotNet.IntegrationTests/UploadApi/MultiMethodsTest.cs index 7c9115eb..7f0153b5 100644 --- a/CloudinaryDotNet.IntegrationTests/UploadApi/MultiMethodsTest.cs +++ b/CloudinaryDotNet.IntegrationTests/UploadApi/MultiMethodsTest.cs @@ -99,7 +99,7 @@ public void TestDownloadMulti() var paramsFromUrl = new MultiParams(new List {url1, url2}); var urlFromUrls = m_cloudinary.DownloadMulti(paramsFromUrl); - var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinary.Api.Account.Cloud + "/image/multi"; + var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinaryUpload.Api.Account.Cloud + "/image/multi"; var uriFromTag = new Uri(urlFromTag); var uriFromUrls = new Uri(urlFromUrls); Assert.True(uriFromTag.ToString().StartsWith(expectedUrl)); @@ -122,10 +122,10 @@ public void TestDownloadMulti() private void AssertMultiResult(MultiResult result, string transformation, string fileFormat) { if (!string.IsNullOrEmpty(transformation)) - Assert.True(result.Url.AbsoluteUri.Contains(transformation)); + Assert.True(result.Url?.AbsoluteUri.Contains(transformation), result.Error?.Message); if (!string.IsNullOrEmpty(fileFormat)) - Assert.True(result.Url.AbsoluteUri.EndsWith($".{fileFormat}")); + Assert.True(result.Url?.AbsoluteUri.EndsWith($".{fileFormat}"), result.Error?.Message); } } } diff --git a/CloudinaryDotNet.IntegrationTests/UploadApi/SpriteMethodsTest.cs b/CloudinaryDotNet.IntegrationTests/UploadApi/SpriteMethodsTest.cs index 14744177..e959714b 100644 --- a/CloudinaryDotNet.IntegrationTests/UploadApi/SpriteMethodsTest.cs +++ b/CloudinaryDotNet.IntegrationTests/UploadApi/SpriteMethodsTest.cs @@ -154,7 +154,7 @@ public void TestDownloadSprite() var paramsFromUrl = new SpriteParams(new List { url1, url2 }); var urlFromUrls = m_cloudinary.DownloadSprite(paramsFromUrl); - var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinary.Api.Account.Cloud + "/image/sprite"; + var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinaryUpload.Api.Account.Cloud + "/image/sprite"; var uriFromTag = new Uri(urlFromTag); var uriFromUrls = new Uri(urlFromUrls); Assert.True(uriFromTag.ToString().StartsWith(expectedUrl)); diff --git a/CloudinaryDotNet.IntegrationTests/UploadApi/UploadMethodsTest.cs b/CloudinaryDotNet.IntegrationTests/UploadApi/UploadMethodsTest.cs index b4f3824a..5cfa8448 100644 --- a/CloudinaryDotNet.IntegrationTests/UploadApi/UploadMethodsTest.cs +++ b/CloudinaryDotNet.IntegrationTests/UploadApi/UploadMethodsTest.cs @@ -169,18 +169,18 @@ public void TestUploadLocalImageTimeout() }; // Save original values - var origAddr = m_cloudinary.Api.ApiBaseAddress; - var origTimeout = m_cloudinary.Api.Timeout; + var origAddr = m_cloudinaryUpload.Api.ApiBaseAddress; + var origTimeout = m_cloudinaryUpload.Api.Timeout; var stopWatch = new Stopwatch(); try { - m_cloudinary.Api.ApiBaseAddress = "https://10.255.255.1"; - m_cloudinary.Api.Timeout = TIMEOUT; + m_cloudinaryUpload.Api.ApiBaseAddress = "https://10.255.255.1"; + m_cloudinaryUpload.Api.Timeout = TIMEOUT; stopWatch.Start(); - m_cloudinary.Upload(uploadParams); + m_cloudinaryUpload.Upload(uploadParams); } catch (Exception) { @@ -188,8 +188,8 @@ public void TestUploadLocalImageTimeout() } finally { - m_cloudinary.Api.ApiBaseAddress = origAddr; - m_cloudinary.Api.Timeout = origTimeout; + m_cloudinaryUpload.Api.ApiBaseAddress = origAddr; + m_cloudinaryUpload.Api.Timeout = origTimeout; stopWatch.Stop(); } diff --git a/CloudinaryDotNet.Tests/Asset/UrlBuilderTest.cs b/CloudinaryDotNet.Tests/Asset/UrlBuilderTest.cs index f16b9df9..9e09b711 100644 --- a/CloudinaryDotNet.Tests/Asset/UrlBuilderTest.cs +++ b/CloudinaryDotNet.Tests/Asset/UrlBuilderTest.cs @@ -329,7 +329,7 @@ public void TestSecureDistributionFromUrl() { // should take secure distribution from url if secure=TRUE - var cloudinary = new CloudinaryDotNet.Cloudinary("cloudinary://a:b@test123/config.secure.distribution.com"); + var cloudinary = new CloudinaryDotNet.CloudinaryUpload("cloudinary://a:b@test123/config.secure.distribution.com"); string url = cloudinary.Api.UrlImgUp.BuildUrl("test"); Assert.AreEqual("https://config.secure.distribution.com/image/upload/test", url); diff --git a/CloudinaryDotNet.Tests/MetaDataTest.cs b/CloudinaryDotNet.Tests/MetaDataTest.cs index 72d1f463..2f104b35 100644 --- a/CloudinaryDotNet.Tests/MetaDataTest.cs +++ b/CloudinaryDotNet.Tests/MetaDataTest.cs @@ -13,12 +13,12 @@ public class MetaDataTest private const string externalIdEnum = "metadata_external_id_enum"; private const string externalIdDelete = "metadata_deletion"; private const string datasourceEntryExternalId = "metadata_datasource_entry_external_id"; - private MockedCloudinary mockedCloudinary; + private MockedCloudinaryAdmin mockedCloudinary; [SetUp] public void SetUp() { - mockedCloudinary = new MockedCloudinary(); + mockedCloudinary = new MockedCloudinaryAdmin(); } /// @@ -132,7 +132,7 @@ public void TestDeleteMetadataField() /// The type of value that can be assigned to the metadata field. /// A unique identification string for the metadata field. /// (Optional) Data source for a given field. - private static void AssertEncodedRequestFields(MockedCloudinary mockedCloudinary, string type, string externalId, + private static void AssertEncodedRequestFields(MockedCloudinaryAdmin mockedCloudinary, string type, string externalId, EntryParams dataSourceEntry = null) { var requestJson = JToken.Parse(mockedCloudinary.HttpRequestContent); diff --git a/CloudinaryDotNet.Tests/MockedCloudinary.cs b/CloudinaryDotNet.Tests/MockedCloudinary.cs index e4179b58..2eba0872 100644 --- a/CloudinaryDotNet.Tests/MockedCloudinary.cs +++ b/CloudinaryDotNet.Tests/MockedCloudinary.cs @@ -7,16 +7,13 @@ namespace CloudinaryDotNet.Tests { - public class MockedCloudinary : Cloudinary + public static class MockHelpers { - public Mock HandlerMock; - public string HttpRequestContent; - private const string cloudName = "test_cloud"; - - public MockedCloudinary(string responseStr = "{}") : base("cloudinary://a:b@test_cloud") + public static Mock SetupMock(this IMockedApi mockedApi, string responseStr) { - HandlerMock = new Mock(); - HandlerMock.Protected() + var mock = new Mock(); + mock + .Protected() .Setup>( "SendAsync", ItExpr.IsAny(), @@ -24,7 +21,7 @@ public MockedCloudinary(string responseStr = "{}") : base("cloudinary://a:b@test .Callback( (httpRequestMessage, cancellationToken) => { - HttpRequestContent = httpRequestMessage.Content? + mockedApi.HttpRequestContent = httpRequestMessage.Content? .ReadAsStringAsync() .GetAwaiter() .GetResult(); @@ -34,26 +31,56 @@ public MockedCloudinary(string responseStr = "{}") : base("cloudinary://a:b@test StatusCode = HttpStatusCode.OK, Content = new StringContent(responseStr) }); - Api.Client = new HttpClient(HandlerMock.Object); + return mock; } - /// - /// Asserts that a given HTTP call was sent with expected parameters. - /// - /// Expected HTTP method type. - /// Expected local part of the called Uri. - public void AssertHttpCall(System.Net.Http.HttpMethod httpMethod, string localPath) + public static void AssertHttpCall( + this IMockedApi mockedApi, + System.Net.Http.HttpMethod httpMethod, + string localPath + ) { - HandlerMock.Protected().Verify( + mockedApi.HandlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is(req => req.Method == httpMethod && - req.RequestUri.LocalPath == $"/v1_1/{cloudName}/{localPath}" && + req.RequestUri.LocalPath == $"/v1_1/{CloudName}/{localPath}" && req.Properties.Count == 0 ), ItExpr.IsAny() ); } + public const string CloudName = "test_cloud"; + } + + public interface IMockedApi + { + Mock HandlerMock { get; set; } + string HttpRequestContent { set; } + } + + internal class MockedCloudinaryAdmin : CloudinaryAdmin, IMockedApi + { + public Mock HandlerMock { get; set; } + public string HttpRequestContent { get; set; } + + public MockedCloudinaryAdmin(string responseStr = "{}") : base($"cloudinary://a:b@{MockHelpers.CloudName}") + { + HandlerMock = this.SetupMock(responseStr); + Api.Client = new HttpClient(HandlerMock.Object); + } + } + + internal class MockedCloudinaryUpload : CloudinaryUpload, IMockedApi + { + public Mock HandlerMock { get; set; } + public string HttpRequestContent { get; set; } + + public MockedCloudinaryUpload(string responseStr = "{}") : base($"cloudinary://a:b@{MockHelpers.CloudName}") + { + HandlerMock = this.SetupMock(responseStr); + Api.Client = new HttpClient(HandlerMock.Object); + } } } diff --git a/CloudinaryDotNet.Tests/SearchTest.cs b/CloudinaryDotNet.Tests/SearchTest.cs index f50fac56..3a56a417 100644 --- a/CloudinaryDotNet.Tests/SearchTest.cs +++ b/CloudinaryDotNet.Tests/SearchTest.cs @@ -7,7 +7,7 @@ namespace CloudinaryDotNet.Tests { public class SearchTest { - private MockedCloudinary m_cloudinary = new MockedCloudinary(); + private MockedCloudinaryAdmin m_cloudinary = new MockedCloudinaryAdmin(); [Test] public void TestShouldNotDuplicateValues() diff --git a/CloudinaryDotNet.Tests/UploadApi/CreateSlideshowMethodsTest.cs b/CloudinaryDotNet.Tests/UploadApi/CreateSlideshowMethodsTest.cs index 9fb40c38..1b104339 100644 --- a/CloudinaryDotNet.Tests/UploadApi/CreateSlideshowMethodsTest.cs +++ b/CloudinaryDotNet.Tests/UploadApi/CreateSlideshowMethodsTest.cs @@ -10,7 +10,7 @@ public class CreateSlideshowMethodsTest [Test] public void TestCreateSlideshowFromManifestTransformation() { - var cloudinary = new MockedCloudinary(); + var cloudinary = new MockedCloudinaryUpload(); const string slideshowManifest = "w_352;h_240;du_5;fps_30;vars_(slides_((media_s64:aHR0cHM6Ly9y" + "ZXMuY2xvdWRpbmFyeS5jb20vZGVtby9pbWFnZS91cGxvYWQvY291cGxl);(media_s64:aH" + @@ -42,7 +42,7 @@ public void TestCreateSlideshowFromManifestTransformation() [Test] public void TestCreateSlideshowFromManifestJson() { - var cloudinary = new MockedCloudinary(); + var cloudinary = new MockedCloudinaryUpload(); const string expectedManifestJson = @"{""w"":848,""h"":480,""du"":6,""fps"":30,""vars"":{""sdur"":500,""tdur"":500,""slides"":"+ diff --git a/CloudinaryDotNet.Tests/UploadPresetsTest.cs b/CloudinaryDotNet.Tests/UploadPresetsTest.cs index 3eeb5a73..c6779d72 100644 --- a/CloudinaryDotNet.Tests/UploadPresetsTest.cs +++ b/CloudinaryDotNet.Tests/UploadPresetsTest.cs @@ -14,18 +14,18 @@ public class UploadPresetsTest private const string evalStr = "if (resource_info['width'] > 450) " + "{ upload_options['quality_analysis'] = true }; " + "upload_options['context'] = 'width = ' + resource_info['width']"; - private MockedCloudinary mockedCloudinary; + private MockedCloudinaryAdmin mockedCloudinary; [SetUp] public void SetUp() { - mockedCloudinary = new MockedCloudinary(); + mockedCloudinary = new MockedCloudinaryAdmin(); } [Test] public void TestListUploadPresets() { - var localCloudinaryMock = new MockedCloudinary("{presets: [{eval: 'some value'}]}"); + var localCloudinaryMock = new MockedCloudinaryAdmin("{presets: [{eval: 'some value'}]}"); var result = localCloudinaryMock.ListUploadPresets(); @@ -36,7 +36,7 @@ public void TestListUploadPresets() [Test] public void TestGetUploadPreset() { - var localCloudinaryMock = new MockedCloudinary("{eval: 'some value'}"); + var localCloudinaryMock = new MockedCloudinaryAdmin("{eval: 'some value'}"); var result = localCloudinaryMock.GetUploadPreset(apiTestPreset); diff --git a/CloudinaryDotNet/Api/CloudinaryAdmin.MetadataFields.cs b/CloudinaryDotNet/Api/CloudinaryAdmin.MetadataFields.cs new file mode 100644 index 00000000..94809f1a --- /dev/null +++ b/CloudinaryDotNet/Api/CloudinaryAdmin.MetadataFields.cs @@ -0,0 +1,130 @@ +namespace CloudinaryDotNet +{ + using System; + using System.Collections.Generic; + using CloudinaryDotNet.Actions; + + /// + /// Part of Cloudinary .NET API main class, responsible for metadata fields management. + /// + internal partial class CloudinaryAdmin + { + /// + public MetadataFieldResult AddMetadataField(MetadataFieldCreateParams parameters) + { + var url = Api.ApiUrlMetadataFieldV.BuildUrl(); + var result = CallAdminApiAsync(HttpMethod.POST, url, parameters, null, PrepareHeaders()).GetAwaiter().GetResult(); + return result; + } + + /// + public MetadataFieldListResult ListMetadataFields() + { + var result = CallAdminApiAsync( + HttpMethod.GET, Api.ApiUrlMetadataFieldV.BuildUrl(), null, null).GetAwaiter().GetResult(); + return result; + } + + /// + public MetadataFieldResult GetMetadataField(string fieldExternalId) + { + var url = Api.ApiUrlMetadataFieldV.Add(fieldExternalId).BuildUrl(); + var result = CallAdminApiAsync(HttpMethod.GET, url, null, null).GetAwaiter().GetResult(); + return result; + } + + /// + public MetadataFieldResult UpdateMetadataField(string fieldExternalId, MetadataFieldUpdateParams parameters) + { + if (string.IsNullOrEmpty(fieldExternalId)) + { + throw new ArgumentNullException(nameof(fieldExternalId)); + } + + var url = Api.ApiUrlMetadataFieldV.Add(fieldExternalId).BuildUrl(); + var result = CallAdminApiAsync(HttpMethod.PUT, url, parameters, null, PrepareHeaders()).GetAwaiter().GetResult(); + return result; + } + + /// + public MetadataDataSourceResult UpdateMetadataDataSourceEntries(string fieldExternalId, MetadataDataSourceParams parameters) + { + if (string.IsNullOrEmpty(fieldExternalId)) + { + throw new ArgumentNullException(nameof(fieldExternalId)); + } + + var url = Api.ApiUrlMetadataFieldV.Add(fieldExternalId).Add(Constants.DATASOURCE_MANAGMENT).BuildUrl(); + var result = CallAdminApiAsync(HttpMethod.PUT, url, parameters, null, PrepareHeaders()).GetAwaiter().GetResult(); + return result; + } + + /// + public DelMetadataFieldResult DeleteMetadataField(string fieldExternalId) + { + if (string.IsNullOrEmpty(fieldExternalId)) + { + throw new ArgumentNullException(nameof(fieldExternalId)); + } + + var url = Api.ApiUrlMetadataFieldV.Add(fieldExternalId).BuildUrl(); + var result = CallAdminApiAsync(HttpMethod.DELETE, url, null, null).GetAwaiter().GetResult(); + return result; + } + + /// + public MetadataDataSourceResult DeleteMetadataDataSourceEntries(string fieldExternalId, List entriesExternalIds) + { + var url = PrepareUrlForDatasourceOperation(fieldExternalId, entriesExternalIds, Constants.DATASOURCE_MANAGMENT); + var result = CallAdminApiAsync(HttpMethod.DELETE, url, null, null).GetAwaiter().GetResult(); + return result; + } + + /// + public MetadataDataSourceResult RestoreMetadataDataSourceEntries(string fieldExternalId, List entriesExternalIds) + { + var url = PrepareUrlForDatasourceOperation(fieldExternalId, entriesExternalIds, $"{Constants.DATASOURCE_MANAGMENT}_restore"); + var result = CallAdminApiAsync(HttpMethod.POST, url, null, null).GetAwaiter().GetResult(); + return result; + } + + /// + public MetadataUpdateResult UpdateMetadata(MetadataUpdateParams parameters) + { + var url = GetApiUrlV(). + Add(Api.GetCloudinaryParam(parameters.ResourceType)). + Add(Constants.METADATA). + BuildUrl(); + var result = CallAdminApiAsync(HttpMethod.POST, url, parameters, null).GetAwaiter().GetResult(); + return result; + } + + private static Dictionary PrepareHeaders() + { + var extraHeaders = new Dictionary + { + { + Constants.HEADER_CONTENT_TYPE, + Constants.CONTENT_TYPE_APPLICATION_JSON + }, + }; + + return extraHeaders; + } + + private string PrepareUrlForDatasourceOperation(string fieldExternalId, List entriesExternalIds, string actionName) + { + if (string.IsNullOrEmpty(fieldExternalId)) + { + throw new ArgumentNullException(nameof(fieldExternalId)); + } + + var parameters = new DataSourceEntriesParams(entriesExternalIds); + var urlBuilder = new UrlBuilder( + Api.ApiUrlMetadataFieldV.Add(fieldExternalId).Add(actionName).BuildUrl(), + parameters.ToParamsDictionary()); + var url = urlBuilder.ToString(); + return url; + } + } +} diff --git a/CloudinaryDotNet/Api/CloudinaryAdmin.StreamingProfiles.cs b/CloudinaryDotNet/Api/CloudinaryAdmin.StreamingProfiles.cs new file mode 100644 index 00000000..a97d5d00 --- /dev/null +++ b/CloudinaryDotNet/Api/CloudinaryAdmin.StreamingProfiles.cs @@ -0,0 +1,126 @@ +namespace CloudinaryDotNet +{ + using System; + using System.Threading; + using System.Threading.Tasks; + using CloudinaryDotNet.Actions; + + /// + /// Part of Cloudinary .NET API main class, responsible for streaming profiles management. + /// + internal partial class CloudinaryAdmin + { + /// + public Task CreateStreamingProfileAsync(StreamingProfileCreateParams parameters, CancellationToken? cancellationToken = null) => + CallStreamingProfileApiAsync(HttpMethod.POST, parameters, cancellationToken); + + /// + public StreamingProfileResult CreateStreamingProfile(StreamingProfileCreateParams parameters) => + CallStreamingProfileApi(HttpMethod.POST, parameters); + + /// + public Task UpdateStreamingProfileAsync( + string name, + StreamingProfileUpdateParams parameters, + CancellationToken? cancellationToken = null) + { + ValidateCallStreamingProfileApiParameters(name, parameters); + return CallStreamingProfileApiAsync(HttpMethod.PUT, parameters, cancellationToken); + } + + /// + public StreamingProfileResult UpdateStreamingProfile(string name, StreamingProfileUpdateParams parameters) + { + ValidateCallStreamingProfileApiParameters(name, parameters); + return CallStreamingProfileApi(HttpMethod.PUT, parameters, name); + } + + /// + public Task DeleteStreamingProfileAsync(string name, CancellationToken? cancellationToken = null) + { + ValidateNameForCallStreamingProfileApiParameters(name); + return CallStreamingProfileApiAsync(HttpMethod.DELETE, null, cancellationToken, name); + } + + /// + public StreamingProfileResult DeleteStreamingProfile(string name) + { + ValidateNameForCallStreamingProfileApiParameters(name); + return CallStreamingProfileApi(HttpMethod.DELETE, null, name); + } + + /// + public Task GetStreamingProfileAsync(string name, CancellationToken? cancellationToken = null) + { + ValidateNameForCallStreamingProfileApiParameters(name); + return CallStreamingProfileApiAsync(HttpMethod.GET, null, cancellationToken, name); + } + + /// + public StreamingProfileResult GetStreamingProfile(string name) + { + ValidateNameForCallStreamingProfileApiParameters(name); + return CallStreamingProfileApi(HttpMethod.GET, null, name); + } + + /// + public Task ListStreamingProfilesAsync(CancellationToken? cancellationToken = null) + { + return CallAdminApiAsync( + HttpMethod.GET, + Api.ApiUrlStreamingProfileV.BuildUrl(), + null, + cancellationToken); + } + + /// + public StreamingProfileListResult ListStreamingProfiles() + { + return ListStreamingProfilesAsync().GetAwaiter().GetResult(); + } + + private static void ValidateCallStreamingProfileApiParameters(string name, StreamingProfileUpdateParams parameters) + { + ValidateNameForCallStreamingProfileApiParameters(name); + ValidateStreamingProfileUpdateParams(parameters); + } + + private static void ValidateStreamingProfileUpdateParams(StreamingProfileUpdateParams parameters) + { + if (parameters == null) + { + throw new ArgumentNullException(nameof(parameters)); + } + } + + private static void ValidateNameForCallStreamingProfileApiParameters(string name) + { + if (string.IsNullOrEmpty(name)) + { + throw new ArgumentException("Name parameter should be defined", nameof(name)); + } + } + + private Task CallStreamingProfileApiAsync( + HttpMethod httpMethod, + BaseParams parameters, + CancellationToken? cancellationToken, + string name = null) + { + return CallAdminApiAsync( + httpMethod, + Api.ApiUrlStreamingProfileV.Add(name).BuildUrl(), + parameters, + cancellationToken); + } + + private StreamingProfileResult CallStreamingProfileApi(HttpMethod httpMethod, BaseParams parameters, string name = null) + { + return CallStreamingProfileApiAsync( + httpMethod, + parameters, + null, + name).GetAwaiter().GetResult(); + } + } +} diff --git a/CloudinaryDotNet/Api/CloudinaryAdmin.cs b/CloudinaryDotNet/Api/CloudinaryAdmin.cs new file mode 100644 index 00000000..d8e93231 --- /dev/null +++ b/CloudinaryDotNet/Api/CloudinaryAdmin.cs @@ -0,0 +1,1485 @@ +namespace CloudinaryDotNet +{ + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; + using System.Threading; + using System.Threading.Tasks; + using CloudinaryDotNet.Actions; + + /// + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Reviewed.")] + internal partial class CloudinaryAdmin : ICloudinaryAdmin + { + /// + /// Cloudinary object. + /// + protected internal Api Api; + + /// + /// Initializes a new instance of the class. + /// Default parameterless constructor. Assumes that environment variable CLOUDINARY_URL is set. + /// + public CloudinaryAdmin() + { + Api = new Api(); + } + + /// + /// Initializes a new instance of the class with Cloudinary URL. + /// + /// Cloudinary URL. + public CloudinaryAdmin(string cloudinaryUrl) + { + Api = new Api(cloudinaryUrl); + } + + /// + /// Initializes a new instance of the class with Cloudinary account. + /// + /// Cloudinary account. + public CloudinaryAdmin(Account account) + { + Api = new Api(account); + } + + /// + public Search Search() + { + return new Search(Api); + } + + /// + public Task ListResourceTypesAsync(CancellationToken? cancellationToken = null) + { + return CallAdminApiAsync(HttpMethod.GET, GetResourcesUrl().BuildUrl(), null, cancellationToken); + } + + /// + public ListResourceTypesResult ListResourceTypes() + { + return ListResourceTypesAsync().GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesAsync( + string nextCursor = null, + bool tags = true, + bool context = true, + bool moderations = true, + CancellationToken? cancellationToken = null) + { + var listResourcesParams = new ListResourcesParams() + { + NextCursor = nextCursor, + Tags = tags, + Context = context, + Moderations = moderations, + }; + return ListResourcesAsync(listResourcesParams, cancellationToken); + } + + /// + public ListResourcesResult ListResources( + string nextCursor = null, + bool tags = true, + bool context = true, + bool moderations = true) + { + return ListResourcesAsync(nextCursor, tags, context, moderations) + .GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesByTypeAsync( + string type, + string nextCursor = null, + CancellationToken? cancellationToken = null) + { + var listResourcesParams = new ListResourcesParams() + { + Type = type, + NextCursor = nextCursor, + }; + + return ListResourcesAsync(listResourcesParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByType(string type, string nextCursor = null) + { + return ListResourcesByTypeAsync(type, nextCursor).GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesByPrefixAsync( + string prefix, + string type = "upload", + string nextCursor = null, + CancellationToken? cancellationToken = null) + { + var listResourcesByPrefixParams = new ListResourcesByPrefixParams() + { + Type = type, + Prefix = prefix, + NextCursor = nextCursor, + }; + return ListResourcesAsync(listResourcesByPrefixParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByPrefix( + string prefix, + string type = "upload", + string nextCursor = null) + { + return ListResourcesByPrefixAsync(prefix, type, nextCursor) + .GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesByPrefixAsync( + string prefix, + bool tags, + bool context, + bool moderations, + string type = "upload", + string nextCursor = null, + CancellationToken? cancellationToken = null) + { + var listResourcesByPrefixParams = new ListResourcesByPrefixParams() + { + Tags = tags, + Context = context, + Moderations = moderations, + Type = type, + Prefix = prefix, + NextCursor = nextCursor, + }; + return ListResourcesAsync(listResourcesByPrefixParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByPrefix(string prefix, bool tags, bool context, bool moderations, string type = "upload", string nextCursor = null) + { + return ListResourcesByPrefixAsync(prefix, tags, context, moderations, type, nextCursor) + .GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesByTagAsync( + string tag, + string nextCursor = null, + CancellationToken? cancellationToken = null) + { + var listResourcesByTagParams = new ListResourcesByTagParams() + { + Tag = tag, + NextCursor = nextCursor, + }; + return ListResourcesAsync(listResourcesByTagParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByTag(string tag, string nextCursor = null) + { + return ListResourcesByTagAsync(tag, nextCursor).GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesByPublicIdsAsync( + IEnumerable publicIds, + CancellationToken? cancellationToken = null) + { + var listSpecificResourcesParams = new ListSpecificResourcesParams() + { + PublicIds = new List(publicIds), + }; + return ListResourcesAsync(listSpecificResourcesParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByPublicIds(IEnumerable publicIds) + { + return ListResourcesByPublicIdsAsync(publicIds) + .GetAwaiter().GetResult(); + } + + /// + public Task ListResourceByPublicIdsAsync( + IEnumerable publicIds, + bool tags, + bool context, + bool moderations, + CancellationToken? cancellationToken = null) + { + var listSpecificResourcesParams = new ListSpecificResourcesParams() + { + PublicIds = new List(publicIds), + Tags = tags, + Context = context, + Moderations = moderations, + }; + return ListResourcesAsync(listSpecificResourcesParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourceByPublicIds(IEnumerable publicIds, bool tags, bool context, bool moderations) + { + return ListResourceByPublicIdsAsync(publicIds, tags, context, moderations) + .GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesByModerationStatusAsync( + string kind, + ModerationStatus status, + bool tags = true, + bool context = true, + bool moderations = true, + string nextCursor = null, + CancellationToken? cancellationToken = null) + { + var listResourcesByModerationParams = new ListResourcesByModerationParams() + { + ModerationKind = kind, + ModerationStatus = status, + Tags = tags, + Context = context, + Moderations = moderations, + NextCursor = nextCursor, + }; + return ListResourcesAsync(listResourcesByModerationParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByModerationStatus( + string kind, + ModerationStatus status, + bool tags = true, + bool context = true, + bool moderations = true, + string nextCursor = null) + { + return ListResourcesByModerationStatusAsync(kind, status, tags, context, moderations, nextCursor) + .GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesByContextAsync( + string key, + string value = "", + bool tags = false, + bool context = false, + string nextCursor = null, + CancellationToken? cancellationToken = null) + { + var listResourcesByContextParams = new ListResourcesByContextParams() + { + Key = key, + Value = value, + Tags = tags, + Context = context, + NextCursor = nextCursor, + }; + return ListResourcesAsync(listResourcesByContextParams, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByContext( + string key, + string value = "", + bool tags = false, + bool context = false, + string nextCursor = null) + { + return ListResourcesByContextAsync(key, value, tags, context, nextCursor) + .GetAwaiter().GetResult(); + } + + /// + public Task ListResourcesAsync(ListResourcesParams parameters, CancellationToken? cancellationToken = null) + { + var url = GetListResourcesUrl(parameters); + return CallAdminApiAsync(HttpMethod.GET, url, parameters, cancellationToken); + } + + /// + public ListResourcesResult ListResources(ListResourcesParams parameters) + { + return ListResourcesAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task PublishResourceByPrefixAsync( + string prefix, + PublishResourceParams parameters, + CancellationToken? cancellationToken) + { + return PublishResourceAsync("prefix", prefix, parameters, cancellationToken); + } + + /// + public PublishResourceResult PublishResourceByPrefix(string prefix, PublishResourceParams parameters) + { + return PublishResource("prefix", prefix, parameters); + } + + /// + public Task PublishResourceByTagAsync( + string tag, + PublishResourceParams parameters, + CancellationToken? cancellationToken = null) + { + return PublishResourceAsync("tag", tag, parameters, cancellationToken); + } + + /// + public PublishResourceResult PublishResourceByTag(string tag, PublishResourceParams parameters) + { + return PublishResource("tag", tag, parameters); + } + + /// + [SuppressMessage("Microsoft.Usage", "CA1801: Review unused parameters", Justification = "Reviewed.")] + public Task PublishResourceByIdsAsync( + string tag, + PublishResourceParams parameters, + CancellationToken? cancellationToken) + { + return PublishResourceAsync(string.Empty, string.Empty, parameters, cancellationToken); + } + + /// + [SuppressMessage("Microsoft.Usage", "CA1801: Review unused parameters", Justification = "Reviewed.")] + public PublishResourceResult PublishResourceByIds(string tag, PublishResourceParams parameters) + { + return PublishResource(string.Empty, string.Empty, parameters); + } + + /// + public Task UpdateResourceAccessModeByTagAsync( + string tag, + UpdateResourceAccessModeParams parameters, + CancellationToken? cancellationToken = null) + { + return UpdateResourceAccessModeAsync(Constants.TAG_PARAM_NAME, tag, parameters, cancellationToken); + } + + /// + public UpdateResourceAccessModeResult UpdateResourceAccessModeByTag(string tag, UpdateResourceAccessModeParams parameters) + { + return UpdateResourceAccessMode(Constants.TAG_PARAM_NAME, tag, parameters); + } + + /// + public Task UpdateResourceAccessModeByPrefixAsync( + string prefix, + UpdateResourceAccessModeParams parameters, + CancellationToken? cancellationToken = null) + { + return UpdateResourceAccessModeAsync(Constants.PREFIX_PARAM_NAME, prefix, parameters, cancellationToken); + } + + /// + public UpdateResourceAccessModeResult UpdateResourceAccessModeByPrefix( + string prefix, + UpdateResourceAccessModeParams parameters) + { + return UpdateResourceAccessMode(Constants.PREFIX_PARAM_NAME, prefix, parameters); + } + + /// + public Task UpdateResourceAccessModeByIdsAsync( + UpdateResourceAccessModeParams parameters, CancellationToken? cancellationToken = null) + { + return UpdateResourceAccessModeAsync(string.Empty, string.Empty, parameters, cancellationToken); + } + + /// + public UpdateResourceAccessModeResult UpdateResourceAccessModeByIds(UpdateResourceAccessModeParams parameters) + { + return UpdateResourceAccessMode(string.Empty, string.Empty, parameters); + } + + /// + public Task DeleteDerivedResourcesByTransformAsync(DelDerivedResParams parameters, CancellationToken? cancellationToken = null) + { + UrlBuilder urlBuilder = new UrlBuilder( + GetApiUrlV(). + Add("derived_resources"). + BuildUrl(), + parameters.ToParamsDictionary()); + + return CallAdminApiAsync( + HttpMethod.DELETE, + urlBuilder.ToString(), + parameters, + cancellationToken); + } + + /// + public DelDerivedResResult DeleteDerivedResourcesByTransform(DelDerivedResParams parameters) + { + return DeleteDerivedResourcesByTransformAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task RootFoldersAsync(GetFoldersParams parameters = null, CancellationToken? cancellationToken = null) + { + return CallAdminApiAsync(HttpMethod.GET, GetFolderUrl(parameters: parameters), parameters, cancellationToken); + } + + /// + public GetFoldersResult RootFolders(GetFoldersParams parameters = null) + { + return RootFoldersAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task SubFoldersAsync(string folder, CancellationToken? cancellationToken = null) + { + return SubFoldersAsync(folder, null, cancellationToken); + } + + /// + public Task SubFoldersAsync(string folder, GetFoldersParams parameters, CancellationToken? cancellationToken = null) + { + CheckFolderParameter(folder); + + return CallAdminApiAsync( + HttpMethod.GET, + GetFolderUrl(folder, parameters), + null, + cancellationToken); + } + + /// + public GetFoldersResult SubFolders(string folder, GetFoldersParams parameters = null) + { + return SubFoldersAsync( + folder, + parameters, + null).GetAwaiter().GetResult(); + } + + /// + public Task DeleteFolderAsync(string folder, CancellationToken? cancellationToken = null) + { + var uri = GetFolderUrl(folder); + return CallAdminApiAsync( + HttpMethod.DELETE, + uri, + null, + cancellationToken); + } + + /// + public DeleteFolderResult DeleteFolder(string folder) + { + return DeleteFolderAsync(folder, null).GetAwaiter().GetResult(); + } + + /// + public CreateFolderResult CreateFolder(string folder) + { + return CreateFolderAsync( + folder, + null).GetAwaiter().GetResult(); + } + + /// + public Task CreateFolderAsync(string folder, CancellationToken? cancellationToken = null) + { + CheckIfNotEmpty(folder); + + return CallAdminApiAsync( + HttpMethod.POST, + GetFolderUrl(folder), + null, + cancellationToken); + } + + /// + public Task CreateUploadPresetAsync(UploadPresetParams parameters, CancellationToken? cancellationToken = null) + { + string url = GetApiUrlV(). + Add("upload_presets"). + BuildUrl(); + + return CallAdminApiAsync( + HttpMethod.POST, + url, + parameters, + cancellationToken); + } + + /// + public UploadPresetResult CreateUploadPreset(UploadPresetParams parameters) + { + return CreateUploadPresetAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task UpdateUploadPresetAsync(UploadPresetParams parameters, CancellationToken? cancellationToken = null) => + CallApiAsync(PrepareUploadPresetApiParams(parameters), cancellationToken); + + /// + public UploadPresetResult UpdateUploadPreset(UploadPresetParams parameters) => + CallApi(PrepareUploadPresetApiParams(parameters)); + + /// + public Task GetUploadPresetAsync(string name, CancellationToken? cancellationToken = null) + { + var url = GetApiUrlV() + .Add("upload_presets") + .Add(name) + .BuildUrl(); + + return CallAdminApiAsync( + HttpMethod.GET, + url, + null, + cancellationToken); + } + + /// + public GetUploadPresetResult GetUploadPreset(string name) + { + return GetUploadPresetAsync(name, null).GetAwaiter().GetResult(); + } + + /// + public Task ListUploadPresetsAsync(string nextCursor = null, CancellationToken? cancellationToken = null) + { + return ListUploadPresetsAsync(new ListUploadPresetsParams() { NextCursor = nextCursor }, cancellationToken); + } + + /// + public ListUploadPresetsResult ListUploadPresets(string nextCursor = null) + { + return ListUploadPresets(new ListUploadPresetsParams() { NextCursor = nextCursor }); + } + + /// + public Task ListUploadPresetsAsync(ListUploadPresetsParams parameters, CancellationToken? cancellationToken = null) + { + var urlBuilder = new UrlBuilder( + GetApiUrlV() + .Add("upload_presets") + .BuildUrl(), + parameters.ToParamsDictionary()); + + return CallAdminApiAsync( + HttpMethod.GET, + urlBuilder.ToString(), + parameters, + cancellationToken); + } + + /// + public ListUploadPresetsResult ListUploadPresets(ListUploadPresetsParams parameters) + { + return ListUploadPresetsAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task DeleteUploadPresetAsync(string name, CancellationToken? cancellationToken = null) + { + var url = GetApiUrlV() + .Add("upload_presets") + .Add(name) + .BuildUrl(); + + return CallAdminApiAsync( + HttpMethod.DELETE, + url, + null, + cancellationToken); + } + + /// + public DeleteUploadPresetResult DeleteUploadPreset(string name) + { + return DeleteUploadPresetAsync(name, null).GetAwaiter().GetResult(); + } + + /// + public Task GetUsageAsync(DateTime? date, CancellationToken? cancellationToken = null) + { + string uri = GetUsageUrl(date); + + return CallAdminApiAsync( + HttpMethod.GET, + uri, + null, + cancellationToken); + } + + /// + public UsageResult GetUsage(DateTime? date = null) + { + return GetUsageAsync(date, null).GetAwaiter().GetResult(); + } + + /// + public Task GetUsageAsync(CancellationToken? cancellationToken = null) + { + string uri = GetUsageUrl(null); + + return CallAdminApiAsync( + HttpMethod.GET, + uri, + null, + cancellationToken); + } + + /// + public Task ListTagsAsync(CancellationToken? cancellationToken = null) + { + return ListTagsAsync(new ListTagsParams(), cancellationToken); + } + + /// + public ListTagsResult ListTags() + { + return ListTags(new ListTagsParams()); + } + + /// + public Task ListTagsByPrefixAsync(string prefix, CancellationToken? cancellationToken = null) + { + return ListTagsAsync(new ListTagsParams() { Prefix = prefix }, cancellationToken); + } + + /// + public ListTagsResult ListTagsByPrefix(string prefix) + { + return ListTags(new ListTagsParams() { Prefix = prefix }); + } + + /// + public Task ListTagsAsync(ListTagsParams parameters, CancellationToken? cancellationToken = null) + { + var urlBuilder = new UrlBuilder( + GetApiUrlV(). + ResourceType("tags"). + Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). + BuildUrl(), + parameters.ToParamsDictionary()); + + return CallAdminApiAsync(HttpMethod.GET, urlBuilder.ToString(), parameters, cancellationToken); + } + + /// + public ListTagsResult ListTags(ListTagsParams parameters) + { + return ListTagsAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task ListTransformationsAsync(CancellationToken? cancellationToken = null) + { + return ListTransformationsAsync(new ListTransformsParams(), cancellationToken); + } + + /// + public ListTransformsResult ListTransformations() + { + return ListTransformations(new ListTransformsParams()); + } + + /// + public Task ListTransformationsAsync(ListTransformsParams parameters, CancellationToken? cancellationToken = null) + { + var urlBuilder = new UrlBuilder( + GetApiUrlV(). + ResourceType("transformations"). + BuildUrl(), + parameters.ToParamsDictionary()); + + return CallAdminApiAsync( + HttpMethod.GET, + urlBuilder.ToString(), + parameters, + cancellationToken); + } + + /// + public ListTransformsResult ListTransformations(ListTransformsParams parameters) + { + return ListTransformationsAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task GetTransformAsync(string transform, CancellationToken? cancellationToken = null) + { + return GetTransformAsync(new GetTransformParams() { Transformation = transform }, cancellationToken); + } + + /// + public GetTransformResult GetTransform(string transform) + { + return GetTransform(new GetTransformParams() { Transformation = transform }); + } + + /// + public Task GetTransformAsync(GetTransformParams parameters, CancellationToken? cancellationToken = null) + { + var urlBuilder = new UrlBuilder( + GetApiUrlV(). + ResourceType("transformations"). + BuildUrl(), + parameters.ToParamsDictionary()); + + return CallAdminApiAsync( + HttpMethod.GET, + urlBuilder.ToString(), + parameters, + cancellationToken); + } + + /// + public GetTransformResult GetTransform(GetTransformParams parameters) + { + return GetTransformAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task UpdateResourceAsync(string publicId, ModerationStatus moderationStatus, CancellationToken? cancellationToken = null) + { + return UpdateResourceAsync(new UpdateParams(publicId) { ModerationStatus = moderationStatus }, cancellationToken); + } + + /// + public GetResourceResult UpdateResource(string publicId, ModerationStatus moderationStatus) + { + return UpdateResource(new UpdateParams(publicId) { ModerationStatus = moderationStatus }); + } + + /// + public Task UpdateResourceAsync(UpdateParams parameters, CancellationToken? cancellationToken = null) + { + var url = GetApiUrlV(). + ResourceType("resources"). + Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). + Add(parameters.Type).Add(parameters.PublicId). + BuildUrl(); + + return CallAdminApiAsync(HttpMethod.POST, url, parameters, cancellationToken); + } + + /// + public GetResourceResult UpdateResource(UpdateParams parameters) + { + return UpdateResourceAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task GetResourceAsync(string publicId, CancellationToken? cancellationToken = null) + { + return GetResourceAsync(new GetResourceParams(publicId), cancellationToken); + } + + /// + public GetResourceResult GetResource(string publicId) + { + return GetResource(new GetResourceParams(publicId)); + } + + /// + public Task GetResourceAsync(GetResourceParams parameters, CancellationToken? cancellationToken = null) + { + UrlBuilder urlBuilder = new UrlBuilder( + GetApiUrlV(). + ResourceType("resources"). + Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). + Add(parameters.Type). + Add(parameters.PublicId). + BuildUrl(), + parameters.ToParamsDictionary()); + + return CallAdminApiAsync( + HttpMethod.GET, + urlBuilder.ToString(), + parameters, + cancellationToken); + } + + /// + public GetResourceResult GetResource(GetResourceParams parameters) + { + return GetResourceAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task DeleteDerivedResourcesAsync(params string[] ids) + { + var p = new DelDerivedResParams(); + p.DerivedResources.AddRange(ids); + return DeleteDerivedResourcesAsync(p); + } + + /// + public DelDerivedResResult DeleteDerivedResources(params string[] ids) + { + DelDerivedResParams p = new DelDerivedResParams(); + p.DerivedResources.AddRange(ids); + return DeleteDerivedResources(p); + } + + /// + public Task DeleteDerivedResourcesAsync(DelDerivedResParams parameters, CancellationToken? cancellationToken = null) + { + var urlBuilder = new UrlBuilder( + GetApiUrlV(). + Add("derived_resources"). + BuildUrl(), + parameters.ToParamsDictionary()); + + return CallAdminApiAsync( + HttpMethod.DELETE, + urlBuilder.ToString(), + parameters, + cancellationToken); + } + + /// + public DelDerivedResResult DeleteDerivedResources(DelDerivedResParams parameters) + { + return DeleteDerivedResourcesAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task DeleteResourcesAsync(ResourceType type, params string[] publicIds) + { + var p = new DelResParams() { ResourceType = type }; + p.PublicIds.AddRange(publicIds); + return DeleteResourcesAsync(p); + } + + /// + public DelResResult DeleteResources(ResourceType type, params string[] publicIds) + { + DelResParams p = new DelResParams() { ResourceType = type }; + p.PublicIds.AddRange(publicIds); + return DeleteResources(p); + } + + /// + public Task DeleteResourcesAsync(params string[] publicIds) + { + var p = new DelResParams(); + p.PublicIds.AddRange(publicIds); + return DeleteResourcesAsync(p); + } + + /// + public DelResResult DeleteResources(params string[] publicIds) + { + DelResParams p = new DelResParams(); + p.PublicIds.AddRange(publicIds); + return DeleteResources(p); + } + + /// + public Task DeleteResourcesByPrefixAsync(string prefix, CancellationToken? cancellationToken = null) + { + var p = new DelResParams() { Prefix = prefix }; + return DeleteResourcesAsync(p, cancellationToken); + } + + /// + public DelResResult DeleteResourcesByPrefix(string prefix) + { + DelResParams p = new DelResParams() { Prefix = prefix }; + return DeleteResources(p); + } + + /// + public Task DeleteResourcesByPrefixAsync(string prefix, bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null) + { + var p = new DelResParams() + { + Prefix = prefix, + KeepOriginal = keepOriginal, + NextCursor = nextCursor, + }; + return DeleteResourcesAsync(p, cancellationToken); + } + + /// + public DelResResult DeleteResourcesByPrefix(string prefix, bool keepOriginal, string nextCursor) + { + DelResParams p = new DelResParams() { Prefix = prefix, KeepOriginal = keepOriginal, NextCursor = nextCursor }; + return DeleteResources(p); + } + + /// + public Task DeleteResourcesByTagAsync(string tag, CancellationToken? cancellationToken = null) + { + var p = new DelResParams() { Tag = tag }; + return DeleteResourcesAsync(p, cancellationToken); + } + + /// + public DelResResult DeleteResourcesByTag(string tag) + { + DelResParams p = new DelResParams() { Tag = tag }; + return DeleteResources(p); + } + + /// + public Task DeleteResourcesByTagAsync(string tag, bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null) + { + var p = new DelResParams() + { + Tag = tag, + KeepOriginal = keepOriginal, + NextCursor = nextCursor, + }; + return DeleteResourcesAsync(p, cancellationToken); + } + + /// + public DelResResult DeleteResourcesByTag(string tag, bool keepOriginal, string nextCursor) + { + DelResParams p = new DelResParams() { Tag = tag, KeepOriginal = keepOriginal, NextCursor = nextCursor }; + return DeleteResources(p); + } + + /// + public Task DeleteAllResourcesAsync(CancellationToken? cancellationToken = null) + { + var p = new DelResParams() { All = true }; + return DeleteResourcesAsync(p, cancellationToken); + } + + /// + public DelResResult DeleteAllResources() + { + DelResParams p = new DelResParams() { All = true }; + return DeleteResources(p); + } + + /// + public Task DeleteAllResourcesAsync(bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null) + { + var p = new DelResParams() + { + All = true, + KeepOriginal = keepOriginal, + NextCursor = nextCursor, + }; + return DeleteResourcesAsync(p, cancellationToken); + } + + /// + public DelResResult DeleteAllResources(bool keepOriginal, string nextCursor) + { + DelResParams p = new DelResParams() { All = true, KeepOriginal = keepOriginal, NextCursor = nextCursor }; + return DeleteResources(p); + } + + /// + public Task DeleteResourcesAsync(DelResParams parameters, CancellationToken? cancellationToken = null) + { + var url = GetApiUrlV(). + Add("resources"). + Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)); + + url = string.IsNullOrEmpty(parameters.Tag) + ? url.Add(parameters.Type) + : url.Add("tags").Add(parameters.Tag); + + var urlBuilder = new UrlBuilder(url.BuildUrl(), parameters.ToParamsDictionary()); + + return CallAdminApiAsync( + HttpMethod.DELETE, + urlBuilder.ToString(), + parameters, + cancellationToken); + } + + /// + public DelResResult DeleteResources(DelResParams parameters) + { + return DeleteResourcesAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task RestoreAsync(params string[] publicIds) + { + var restoreParams = new RestoreParams(); + restoreParams.PublicIds.AddRange(publicIds); + + return RestoreAsync(restoreParams); + } + + /// + public RestoreResult Restore(params string[] publicIds) + { + RestoreParams restoreParams = new RestoreParams(); + restoreParams.PublicIds.AddRange(publicIds); + + return Restore(restoreParams); + } + + /// + public Task RestoreAsync(RestoreParams parameters, CancellationToken? cancellationToken = null) + { + var url = GetApiUrlV(). + ResourceType("resources"). + Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). + Add("upload"). + Add("restore").BuildUrl(); + + return CallAdminApiAsync(HttpMethod.POST, url, parameters, cancellationToken); + } + + /// + public RestoreResult Restore(RestoreParams parameters) + { + return RestoreAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task UploadMappingsAsync(UploadMappingParams parameters, CancellationToken? cancellationToken = null) + { + return CallUploadMappingsApiAsync(HttpMethod.GET, parameters, cancellationToken); + } + + /// + public UploadMappingResults UploadMappings(UploadMappingParams parameters) + { + return CallUploadMappingsApi(HttpMethod.GET, parameters); + } + + /// + public Task UploadMappingAsync(string folder, CancellationToken? cancellationToken = null) + { + if (string.IsNullOrEmpty(folder)) + { + throw new ArgumentException("Folder name is required.", nameof(folder)); + } + + var parameters = new UploadMappingParams() { Folder = folder }; + + return CallUploadMappingsApiAsync(HttpMethod.GET, parameters, cancellationToken); + } + + /// + public UploadMappingResults UploadMapping(string folder) + { + if (string.IsNullOrEmpty(folder)) + { + throw new ArgumentException("Folder must be specified."); + } + + var parameters = new UploadMappingParams() { Folder = folder }; + + return CallUploadMappingsApi(HttpMethod.GET, parameters); + } + + /// + public Task CreateUploadMappingAsync(string folder, string template, CancellationToken? cancellationToken = null) + { + var parameters = CreateUploadMappingParams(folder, template); + return CallUploadMappingsApiAsync(HttpMethod.POST, parameters, cancellationToken); + } + + /// + public UploadMappingResults CreateUploadMapping(string folder, string template) + { + var parameters = CreateUploadMappingParams(folder, template); + return CallUploadMappingsApi(HttpMethod.POST, parameters); + } + + /// + public Task UpdateUploadMappingAsync(string folder, string newTemplate, CancellationToken? cancellationToken = null) + { + var parameters = CreateUploadMappingParams(folder, newTemplate); + return CallUploadMappingsApiAsync(HttpMethod.PUT, parameters, cancellationToken); + } + + /// + public UploadMappingResults UpdateUploadMapping(string folder, string newTemplate) + { + var parameters = CreateUploadMappingParams(folder, newTemplate); + return CallUploadMappingsApi(HttpMethod.PUT, parameters); + } + + /// + public Task DeleteUploadMappingAsync(CancellationToken? cancellationToken = null) + { + return DeleteUploadMappingAsync(string.Empty, cancellationToken); + } + + /// + public UploadMappingResults DeleteUploadMapping() + { + return DeleteUploadMapping(string.Empty); + } + + /// + public Task DeleteUploadMappingAsync(string folder, CancellationToken? cancellationToken = null) + { + var parameters = new UploadMappingParams { Folder = folder }; + return CallUploadMappingsApiAsync(HttpMethod.DELETE, parameters, cancellationToken); + } + + /// + public UploadMappingResults DeleteUploadMapping(string folder) + { + var parameters = new UploadMappingParams { Folder = folder }; + return CallUploadMappingsApi(HttpMethod.DELETE, parameters); + } + + /// + public Task UpdateTransformAsync(UpdateTransformParams parameters, CancellationToken? cancellationToken = null) + { + var httpMethod = HttpMethod.PUT; + var url = GetTransformationUrl(httpMethod, parameters); + + return CallAdminApiAsync(httpMethod, url, parameters, cancellationToken); + } + + /// + public UpdateTransformResult UpdateTransform(UpdateTransformParams parameters) + { + return UpdateTransformAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task CreateTransformAsync(CreateTransformParams parameters, CancellationToken? cancellationToken = null) + { + var httpMethod = HttpMethod.POST; + var url = GetTransformationUrl(httpMethod, parameters); + + return CallAdminApiAsync(httpMethod, url, parameters, cancellationToken); + } + + /// + public TransformResult CreateTransform(CreateTransformParams parameters) + { + return CreateTransformAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + public Task DeleteTransformAsync(string transformName, CancellationToken? cancellationToken = null) + { + var httpMethod = HttpMethod.DELETE; + var url = GetTransformationUrl(httpMethod, new DeleteTransformParams() { Transformation = transformName }); + + return CallAdminApiAsync( + httpMethod, + url, + null, + cancellationToken); + } + + /// + public TransformResult DeleteTransform(string transformName) + { + return DeleteTransformAsync(transformName, null).GetAwaiter().GetResult(); + } + + private static void CheckIfNotEmpty(string folder) + { + if (string.IsNullOrEmpty(folder)) + { + throw new ArgumentException("Folder must be set."); + } + } + + private static void CheckFolderParameter(string folder) + { + if (string.IsNullOrEmpty(folder)) + { + throw new ArgumentException( + "folder must be set. Please use RootFolders() to get list of folders in root."); + } + } + + private static UploadMappingParams CreateUploadMappingParams(string folder, string template) + { + if (string.IsNullOrEmpty(folder)) + { + throw new ArgumentException("Folder property must be specified."); + } + + if (string.IsNullOrEmpty(template)) + { + throw new ArgumentException("Template must be specified."); + } + + var parameters = new UploadMappingParams() + { + Folder = folder, + Template = template, + }; + return parameters; + } + + private UploadPresetApiParams PrepareUploadPresetApiParams(UploadPresetParams parameters) + { + var paramsCopy = (UploadPresetParams)parameters.Copy(); + paramsCopy.Name = null; + + var url = GetApiUrlV() + .Add("upload_presets") + .Add(parameters.Name) + .BuildUrl(); + + return new UploadPresetApiParams(HttpMethod.PUT, url, paramsCopy); + } + + private string GetFolderUrl(string folder = null, GetFoldersParams parameters = null) + { + var urlWithoutParams = GetApiUrlV().Add("folders").Add(folder).BuildUrl(); + + return (parameters != null) ? new UrlBuilder(urlWithoutParams, parameters.ToParamsDictionary()).ToString() : urlWithoutParams; + } + + private string GetUsageUrl(DateTime? date) + { + var url = GetApiUrlV().Action("usage"); + + if (date.HasValue) + { + url.Add(date.Value.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture)); + } + + return url.BuildUrl(); + } + + private string GetListResourcesUrl(ListResourcesParams parameters) + { + var url = GetResourcesUrl().Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)); + + switch (parameters) + { + case ListResourcesByTagParams tagParams when !string.IsNullOrEmpty(tagParams.Tag): + url + .Add("tags") + .Add(tagParams.Tag); + + break; + case ListResourcesByModerationParams modParams when !string.IsNullOrEmpty(modParams.ModerationKind): + url + .Add("moderations") + .Add(modParams.ModerationKind) + .Add(Api.GetCloudinaryParam(modParams.ModerationStatus)); + + break; + case ListResourcesByContextParams _: + url.Add("context"); + + break; + } + + var urlBuilder = new UrlBuilder( + url.BuildUrl(), + parameters.ToParamsDictionary()); + + var s = urlBuilder.ToString(); + return s; + } + + private Task PublishResourceAsync( + string byKey, + string value, + PublishResourceParams parameters, + CancellationToken? cancellationToken) + { + if (!string.IsNullOrWhiteSpace(byKey) && !string.IsNullOrWhiteSpace(value)) + { + parameters.AddCustomParam(byKey, value); + } + + Url url = GetApiUrlV() + .Add("resources") + .Add(parameters.ResourceType.ToString().ToLowerInvariant()) + .Add("publish_resources"); + + return CallAdminApiAsync(HttpMethod.POST, url.BuildUrl(), parameters, cancellationToken); + } + + private PublishResourceResult PublishResource(string byKey, string value, PublishResourceParams parameters) + { + return PublishResourceAsync(byKey, value, parameters, null).GetAwaiter().GetResult(); + } + + private Task UpdateResourceAccessModeAsync( + string byKey, + string value, + UpdateResourceAccessModeParams parameters, + CancellationToken? cancellationToken = null) + { + if (!string.IsNullOrWhiteSpace(byKey) && !string.IsNullOrWhiteSpace(value)) + { + parameters.AddCustomParam(byKey, value); + } + + var url = GetApiUrlV() + .Add(Constants.RESOURCES_API_URL) + .Add(parameters.ResourceType.ToString().ToLowerInvariant()) + .Add(parameters.Type) + .Add(Constants.UPDATE_ACESS_MODE); + + return CallAdminApiAsync( + HttpMethod.POST, + url.BuildUrl(), + parameters, + cancellationToken); + } + + private UpdateResourceAccessModeResult UpdateResourceAccessMode(string byKey, string value, UpdateResourceAccessModeParams parameters) + { + return UpdateResourceAccessModeAsync(byKey, value, parameters).GetAwaiter().GetResult(); + } + + private Url GetResourcesUrl() => GetApiUrlV().ResourceType("resources"); + + private Task CallAdminApiAsync( + HttpMethod httpMethod, + string url, + BaseParams parameters, + CancellationToken? cancellationToken, + Dictionary extraHeaders = null) + where T : BaseResult, new() + { + return Api.CallApiAsync( + httpMethod, + url, + parameters, + null, + extraHeaders, + cancellationToken); + } + + private string GetTransformationUrl(HttpMethod httpMethod, BaseParams parameters) + { + var url = GetApiUrlV(). + ResourceType("transformations"). + BuildUrl(); + + if (parameters != null && (httpMethod == HttpMethod.GET || httpMethod == HttpMethod.DELETE)) + { + url = new UrlBuilder(url, parameters.ToParamsDictionary()).ToString(); + } + + return url; + } + + /// + /// Calls an upload mappings API. + /// + /// HTTP method. + /// Parameters for Mapping of folders to URL prefixes for dynamic image fetching from + /// existing online locations. + /// Parsed response after Upload mappings manipulation. + private UploadMappingResults CallUploadMappingsApi(HttpMethod httpMethod, UploadMappingParams parameters) + { + return CallUploadMappingsApiAsync(httpMethod, parameters).GetAwaiter().GetResult(); + } + + /// + /// Calls an upload mappings API asynchronously. + /// + /// HTTP method. + /// Parameters for Mapping of folders to URL prefixes for dynamic image fetching from + /// existing online locations. + /// (Optional) Cancellation token. + /// Parsed response after Upload mappings manipulation. + private Task CallUploadMappingsApiAsync(HttpMethod httpMethod, UploadMappingParams parameters, CancellationToken? cancellationToken = null) + { + var url = (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) + ? GetUploadMappingUrl() + : GetUploadMappingUrl(parameters); + + return CallAdminApiAsync( + httpMethod, + url, + parameters, + cancellationToken); + } + + /// + /// Call api with specified parameters asynchronously. + /// + /// New parameters for upload preset. + /// (Optional) Cancellation token. + private Task CallApiAsync(UploadPresetApiParams apiParams, CancellationToken? cancellationToken = null) + where T : BaseResult, new() => + CallAdminApiAsync(apiParams.HttpMethod, apiParams.Url, apiParams.ParamsCopy, cancellationToken); + + /// + /// Call api with specified parameters. + /// + /// New parameters for upload preset. + private T CallApi(UploadPresetApiParams apiParams) + where T : BaseResult, new() => + CallApiAsync(apiParams).GetAwaiter().GetResult(); + + private string GetUploadMappingUrl(UploadMappingParams parameters) + { + var uri = GetUploadMappingUrl(); + return (parameters == null) ? uri : new UrlBuilder(uri, parameters.ToParamsDictionary()).ToString(); + } + + private string GetUploadMappingUrl() + { + return GetApiUrlV(). + ResourceType("upload_mappings"). + BuildUrl(); + } + + /// + /// Get default API URL with version. + /// + /// URL of the API. + private Url GetApiUrlV() + { + return Api.ApiUrlV; + } + + /// + /// Private helper class for specifying parameters for upload preset api call. + /// + private class UploadPresetApiParams + { + /// + /// Initializes a new instance of the class. + /// + /// Http request method. + /// Url for api call. + /// Parameters of the upload preset. + public UploadPresetApiParams( + HttpMethod httpMethod, + string url, + UploadPresetParams paramsCopy) + { + Url = url; + ParamsCopy = paramsCopy; + HttpMethod = httpMethod; + } + + /// + /// Gets url for api call. + /// + public string Url { get; private set; } + + /// + /// Gets parameters of the upload preset. + /// + public UploadPresetParams ParamsCopy { get; private set; } + + /// + /// Gets http request method. + /// + public HttpMethod HttpMethod { get; private set; } + } + } +} diff --git a/CloudinaryDotNet/Api/CloudinaryUpload.cs b/CloudinaryDotNet/Api/CloudinaryUpload.cs new file mode 100644 index 00000000..b5d7088f --- /dev/null +++ b/CloudinaryDotNet/Api/CloudinaryUpload.cs @@ -0,0 +1,930 @@ +namespace CloudinaryDotNet +{ + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; + using System.Linq; + using System.Net; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using CloudinaryDotNet.Actions; + using Newtonsoft.Json.Linq; + + /// + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Reviewed.")] + internal class CloudinaryUpload : ICloudinaryUpload + { + /// + /// Resource type 'image'. + /// + internal const string RESOURCE_TYPE_IMAGE = "image"; + + /// + /// Default chunk (buffer) size for upload large files. + /// + internal const int DEFAULT_CHUNK_SIZE = 20 * 1024 * 1024; // 20 MB + + /// + /// Cloudinary object. + /// + protected internal Api Api; + + /// + /// Action 'generate_archive'. + /// + protected const string ACTION_GENERATE_ARCHIVE = "generate_archive"; + + /// + /// Initializes a new instance of the class. + /// Default parameterless constructor. Assumes that environment variable CLOUDINARY_URL is set. + /// + public CloudinaryUpload() + { + Api = new Api(); + } + + /// + /// Initializes a new instance of the class with Cloudinary URL. + /// + /// Cloudinary URL. + public CloudinaryUpload(string cloudinaryUrl) + { + Api = new Api(cloudinaryUrl); + } + + /// + /// Initializes a new instance of the class with Cloudinary account. + /// + /// Cloudinary account. + public CloudinaryUpload(Account account) + { + Api = new Api(account); + } + + /// + public Task UploadAsync(ImageUploadParams parameters, CancellationToken? cancellationToken = null) + { + return UploadAsync(parameters, cancellationToken); + } + + /// + public ImageUploadResult Upload(ImageUploadParams parameters) + { + return Upload(parameters); + } + + /// + public Task UploadAsync(VideoUploadParams parameters, CancellationToken? cancellationToken = null) + { + return UploadAsync(parameters, cancellationToken); + } + + /// + public VideoUploadResult Upload(VideoUploadParams parameters) + { + return Upload(parameters); + } + + /// + public Task UploadAsync( + string resourceType, + IDictionary parameters, + FileDescription fileDescription, + CancellationToken? cancellationToken = null) + { + var uri = GetUploadUrl(resourceType); + + fileDescription.Reset(); + + var dict = NormalizeParameters(parameters); + + return CallUploadApiAsync(uri, dict, cancellationToken, fileDescription); + } + + /// + public RawUploadResult Upload(string resourceType, IDictionary parameters, FileDescription fileDescription) + { + return UploadAsync(resourceType, parameters, fileDescription).GetAwaiter().GetResult(); + } + + /// + public Task UploadAsync(RawUploadParams parameters, string type = "auto", CancellationToken? cancellationToken = null) + { + string uri = Api.ApiUrlImgUpV.ResourceType(type).BuildUrl(); + + parameters.File.Reset(); + + return CallUploadApiAsync( + HttpMethod.POST, + uri, + parameters, + cancellationToken, + parameters.File); + } + + /// + public RawUploadResult Upload(RawUploadParams parameters, string type = "auto") + { + return UploadAsync(parameters, type, null).GetAwaiter().GetResult(); + } + + /// + public Task UploadLargeRawAsync( + BasicRawUploadParams parameters, + int bufferSize = DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null) + { + return UploadLargeAsync(parameters, bufferSize, cancellationToken); + } + + /// + public RawUploadResult UploadLargeRaw(BasicRawUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + { + return UploadLarge(parameters, bufferSize); + } + + /// + public Task UploadLargeAsync( + RawUploadParams parameters, + int bufferSize = DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null) + { + return UploadLargeAsync(parameters, bufferSize, cancellationToken); + } + + /// + public RawUploadResult UploadLarge(RawUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + { + return UploadLarge(parameters, bufferSize); + } + + /// + public Task UploadLargeAsync( + ImageUploadParams parameters, + int bufferSize = DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null) + { + return UploadLargeAsync(parameters, bufferSize, cancellationToken); + } + + /// + public ImageUploadResult UploadLarge(ImageUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + { + return UploadLarge(parameters, bufferSize); + } + + /// + public Task UploadLargeAsync( + VideoUploadParams parameters, + int bufferSize = DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null) + { + return UploadLargeAsync(parameters, bufferSize, cancellationToken); + } + + /// + public VideoUploadResult UploadLarge(VideoUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + { + return UploadLarge(parameters, bufferSize); + } + + /// + public async Task UploadLargeAsync( + BasicRawUploadParams parameters, + int bufferSize = DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null) + where T : UploadResult, new() + { + CheckUploadParameters(parameters); + + if (parameters.File.IsRemote) + { + return await UploadAsync(parameters).ConfigureAwait(false); + } + + var internalParams = new UploadLargeParams(parameters, bufferSize, Api); + T result = null; + + while (!parameters.File.Eof) + { + UpdateContentRange(internalParams); + result = await CallUploadApiAsync( + HttpMethod.POST, + internalParams.Url, + parameters, + cancellationToken, + parameters.File, + internalParams.Headers).ConfigureAwait(false); + CheckUploadResult(result); + } + + return result; + } + + /// + public T UploadLarge(BasicRawUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + where T : UploadResult, new() + { + return UploadLargeAsync(parameters, bufferSize).GetAwaiter().GetResult(); + } + + /// + public Task RenameAsync( + string fromPublicId, + string toPublicId, + bool overwrite = false, + CancellationToken? cancellationToken = null) + { + return RenameAsync( + new RenameParams(fromPublicId, toPublicId) + { + Overwrite = overwrite, + }, + cancellationToken); + } + + /// + public RenameResult Rename(string fromPublicId, string toPublicId, bool overwrite = false) + { + var renameParams = new RenameParams(fromPublicId, toPublicId) + { + Overwrite = overwrite, + }; + + return RenameAsync(renameParams).GetAwaiter().GetResult(); + } + + /// + public Task RenameAsync(RenameParams parameters, CancellationToken? cancellationToken = null) + { + var uri = GetRenameUrl(parameters); + return CallUploadApiAsync( + HttpMethod.POST, + uri, + parameters, + cancellationToken); + } + + /// + public RenameResult Rename(RenameParams parameters) + { + return RenameAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task DestroyAsync(DeletionParams parameters) + { + string uri = Api.ApiUrlImgUpV.ResourceType( + ApiShared.GetCloudinaryParam(parameters.ResourceType)). + Action("destroy").BuildUrl(); + + return CallUploadApiAsync(HttpMethod.POST, uri, parameters, null); + } + + /// + public DeletionResult Destroy(DeletionParams parameters) + { + return DestroyAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public string DownloadBackedUpAsset(string assetId, string versionId) + { + Utils.ShouldNotBeEmpty(() => assetId); + Utils.ShouldNotBeEmpty(() => versionId); + + var parameters = new SortedDictionary + { + { "asset_id", assetId }, + { "version_id", versionId }, + }; + + var urlBuilder = new UrlBuilder(GetApiUrlV().Action("download_backup").BuildUrl()); + return GetDownloadUrl(urlBuilder, parameters); + } + + /// + public Task TagAsync(TagParams parameters, CancellationToken? cancellationToken = null) + { + string uri = GetApiUrlV() + .ResourceType(Api.GetCloudinaryParam(parameters.ResourceType)) + .Action(Constants.TAGS_MANGMENT) + .BuildUrl(); + + return CallUploadApiAsync(HttpMethod.POST, uri, parameters, cancellationToken); + } + + /// + public TagResult Tag(TagParams parameters) + { + return TagAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task ContextAsync(ContextParams parameters, CancellationToken? cancellationToken = null) + { + string uri = Api.ApiUrlImgUpV.ResourceType(ApiShared.GetCloudinaryParam(parameters.ResourceType)).Action(Constants.CONTEXT_MANAGMENT).BuildUrl(); + + return CallUploadApiAsync( + HttpMethod.POST, + uri, + parameters, + cancellationToken); + } + + /// + public ContextResult Context(ContextParams parameters) + { + return ContextAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task ExplicitAsync(ExplicitParams parameters, CancellationToken? cancellationToken = null) + { + string uri = GetApiUrlV() + .ResourceType(Api.GetCloudinaryParam(parameters.ResourceType)) + .Action("explicit") + .BuildUrl(); + + return CallUploadApiAsync( + HttpMethod.POST, + uri, + parameters, + cancellationToken); + } + + /// + public ExplicitResult Explicit(ExplicitParams parameters) + { + return ExplicitAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task ExplodeAsync(ExplodeParams parameters, CancellationToken? cancellationToken = null) + { + var url = Api.ApiUrlImgUpV. + Action("explode"). + BuildUrl(); + + return CallUploadApiAsync( + HttpMethod.POST, + url, + parameters, + cancellationToken); + } + + /// + public ExplodeResult Explode(ExplodeParams parameters) + { + return ExplodeAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public Task CreateZipAsync(ArchiveParams parameters, CancellationToken? cancellationToken = null) + { + parameters.TargetFormat(ArchiveFormat.Zip); + return CreateArchiveAsync(parameters, cancellationToken); + } + + /// + public ArchiveResult CreateZip(ArchiveParams parameters) + { + parameters.TargetFormat(ArchiveFormat.Zip); + return CreateArchive(parameters); + } + + /// + public Task CreateArchiveAsync(ArchiveParams parameters, CancellationToken? cancellationToken = null) + { + Url url = GetApiUrlV().ResourceType(RESOURCE_TYPE_IMAGE).Action(ACTION_GENERATE_ARCHIVE); + + if (!string.IsNullOrEmpty(parameters.ResourceType())) + { + url.ResourceType(parameters.ResourceType()); + } + + parameters.Mode(ArchiveCallMode.Create); + return CallUploadApiAsync( + HttpMethod.POST, + url.BuildUrl(), + parameters, + cancellationToken); + } + + /// + public ArchiveResult CreateArchive(ArchiveParams parameters) + { + return CreateArchiveAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public string DownloadArchiveUrl(ArchiveParams parameters) + { + parameters.Mode(ArchiveCallMode.Download); + + UrlBuilder urlBuilder = new UrlBuilder( + GetApiUrlV(). + ResourceType(parameters.ResourceType()). + Action(ACTION_GENERATE_ARCHIVE). + BuildUrl()); + + return GetDownloadUrl(urlBuilder, parameters.ToParamsDictionary()); + } + + /// + public string DownloadFolder(string folderPath, ArchiveParams parameters = null) + { + var downloadParameters = parameters ?? new ArchiveParams(); + + downloadParameters.Prefixes(new List { folderPath }); + downloadParameters.ResourceType(Constants.RESOURCE_TYPE_ALL); + + return DownloadArchiveUrl(downloadParameters); + } + + /// + public string DownloadZip(string tag, Transformation transform, string resourceType = RESOURCE_TYPE_IMAGE) + { + if (string.IsNullOrEmpty(tag)) + { + throw new ArgumentException("Tag should be specified!"); + } + + var urlBuilder = new UrlBuilder( + GetApiUrlV() + .ResourceType(resourceType) + .Action("download_tag.zip") + .BuildUrl()); + + var parameters = new SortedDictionary + { + { "tag", tag }, + }; + + if (transform != null) + { + parameters.Add("transformation", transform.Generate()); + } + + return GetDownloadUrl(urlBuilder, parameters); + } + + /// + public string DownloadPrivate( + string publicId, + bool? attachment = null, + string format = "", + string type = "", + long? expiresAt = null, + string resourceType = RESOURCE_TYPE_IMAGE) + { + if (string.IsNullOrEmpty(publicId)) + { + throw new ArgumentException("The image public ID is missing."); + } + + var urlBuilder = new UrlBuilder( + GetApiUrlV() + .ResourceType(resourceType) + .Action("download") + .BuildUrl()); + + var parameters = new SortedDictionary + { + { "public_id", publicId }, + }; + + if (!string.IsNullOrEmpty(format)) + { + parameters.Add("format", format); + } + + if (attachment != null) + { + parameters.Add("attachment", (bool)attachment ? "true" : "false"); + } + + if (!string.IsNullOrEmpty(type)) + { + parameters.Add("type", type); + } + + if (expiresAt != null) + { + parameters.Add("expires_at", expiresAt); + } + + return GetDownloadUrl(urlBuilder, parameters); + } + + /// + public Task MakeSpriteAsync(SpriteParams parameters, CancellationToken? cancellationToken = null) + { + var url = Api.ApiUrlImgUpV. + Action(Constants.ACTION_NAME_SPRITE). + BuildUrl(); + + return CallUploadApiAsync( + HttpMethod.POST, + url, + parameters, + cancellationToken); + } + + /// + public SpriteResult MakeSprite(SpriteParams parameters) + { + return MakeSpriteAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public string DownloadSprite(SpriteParams parameters) + { + parameters.Mode = ArchiveCallMode.Download; + var urlBuilder = new UrlBuilder( + Api.ApiUrlImgUpV. + Action(Constants.ACTION_NAME_SPRITE). + BuildUrl()); + + return GetDownloadUrl(urlBuilder, parameters.ToParamsDictionary()); + } + + /// + public Task MultiAsync(MultiParams parameters, CancellationToken? cancellationToken = null) + { + var url = Api.ApiUrlImgUpV. + Action(Constants.ACTION_NAME_MULTI). + BuildUrl(); + + return CallUploadApiAsync( + HttpMethod.POST, + url, + parameters, + cancellationToken); + } + + /// + public MultiResult Multi(MultiParams parameters) + { + return MultiAsync(parameters).GetAwaiter().GetResult(); + } + + /// + public string DownloadMulti(MultiParams parameters) + { + parameters.Mode = ArchiveCallMode.Download; + var urlBuilder = new UrlBuilder( + Api.ApiUrlImgUpV. + Action(Constants.ACTION_NAME_MULTI). + BuildUrl()); + + return GetDownloadUrl(urlBuilder, parameters.ToParamsDictionary()); + } + + /// + public Task TextAsync(string text, CancellationToken? cancellationToken = null) + { + return TextAsync(new TextParams(text), cancellationToken); + } + + /// + public TextResult Text(string text) + { + return Text(new TextParams(text)); + } + + /// + public Task TextAsync(TextParams parameters, CancellationToken? cancellationToken = null) + { + string uri = Api.ApiUrlImgUpV.Action("text").BuildUrl(); + + return CallUploadApiAsync( + HttpMethod.POST, + uri, + parameters, + cancellationToken); + } + + /// + public TextResult Text(TextParams parameters) + { + return TextAsync(parameters).GetAwaiter().GetResult(); + } + + /// + /// Creates auto-generated video slideshow. + /// + /// Parameters for generating the slideshow. + /// The public id of the generated slideshow. + public CreateSlideshowResult CreateSlideshow(CreateSlideshowParams parameters) + { + return CreateSlideshowAsync(parameters).GetAwaiter().GetResult(); + } + + /// + /// Creates auto-generated video slideshow asynchronously. + /// + /// Parameters for generating the slideshow. + /// (Optional) Cancellation token. + /// The public id of the generated slideshow. + public Task CreateSlideshowAsync(CreateSlideshowParams parameters, CancellationToken? cancellationToken = null) + { + string uri = Api.ApiUrlVideoUpV.Action("create_slideshow").BuildUrl(); + + return CallUploadApiAsync( + HttpMethod.POST, + uri, + parameters, + cancellationToken); + } + + /// + public string GetCloudinaryJsConfig(bool directUpload = false, string dir = "") + { + if (string.IsNullOrEmpty(dir)) + { + dir = "/Scripts"; + } + + StringBuilder sb = new StringBuilder(1000); + + AppendScriptLine(sb, dir, "jquery.ui.widget.js"); + AppendScriptLine(sb, dir, "jquery.iframe-transport.js"); + AppendScriptLine(sb, dir, "jquery.fileupload.js"); + AppendScriptLine(sb, dir, "jquery.cloudinary.js"); + + if (directUpload) + { + AppendScriptLine(sb, dir, "canvas-to-blob.min.js"); + AppendScriptLine(sb, dir, "jquery.fileupload-image.js"); + AppendScriptLine(sb, dir, "jquery.fileupload-process.js"); + AppendScriptLine(sb, dir, "jquery.fileupload-validate.js"); + AppendScriptLine(sb, dir, "load-image.min.js"); + } + + var cloudinaryParams = new JObject( + new JProperty[] + { + new JProperty("cloud_name", Api.Account.Cloud), + new JProperty("api_key", Api.Account.ApiKey), + new JProperty("private_cdn", Api.UsePrivateCdn), + new JProperty("cdn_subdomain", Api.CSubDomain), + }); + + if (!string.IsNullOrEmpty(Api.PrivateCdn)) + { + cloudinaryParams.Add("secure_distribution", Api.PrivateCdn); + } + + sb.AppendLine(""); + + return sb.ToString(); + } + + private static void AppendScriptLine(StringBuilder sb, string dir, string script) + { + sb.Append(""); + } + + private static SortedDictionary NormalizeParameters(IDictionary parameters) + { + if (parameters == null) + { + return new SortedDictionary(); + } + + return parameters as SortedDictionary ?? new SortedDictionary(parameters); + } + + private static void CheckUploadResult(T result) + where T : UploadResult, new() + { + if (result.StatusCode != HttpStatusCode.OK) + { + var error = result.Error != null ? result.Error.Message : "Unknown error"; + throw new Exception( + $"An error has occured while uploading file (status code: {result.StatusCode}). {error}"); + } + } + + private static void CheckUploadParameters(BasicRawUploadParams parameters) + { + if (parameters == null) + { + throw new ArgumentNullException(nameof(parameters), "Upload parameters should be defined"); + } + + if (parameters.File == null) + { + throw new ArgumentException("Parameters.File parameter should be defined"); + } + } + + private static void UpdateContentRange(UploadLargeParams internalParams) + { + var fileDescription = internalParams.Parameters.File; + var fileLength = fileDescription.GetFileLength(); + var startOffset = fileDescription.BytesSent; + var endOffset = startOffset + Math.Min(internalParams.BufferSize, fileLength - startOffset) - 1; + + internalParams.Headers["Content-Range"] = $"bytes {startOffset}-{endOffset}/{fileLength}"; + } + + private Task CallUploadApiAsync( + HttpMethod httpMethod, + string url, + BaseParams parameters, + CancellationToken? cancellationToken, + FileDescription fileDescription = null, + Dictionary extraHeaders = null) + where T : BaseResult, new() + { + return Api.CallApiAsync( + httpMethod, + url, + parameters, + fileDescription, + extraHeaders, + cancellationToken); + } + + private Task CallUploadApiAsync( + string url, + SortedDictionary parameters, + CancellationToken? cancellationToken, + FileDescription fileDescription = null) + { + return Api.CallAndParseAsync( + HttpMethod.POST, + url, + parameters, + fileDescription, + null, + cancellationToken); + } + + private string GetUploadUrl(string resourceType) + { + return GetApiUrlV().Action(Constants.ACTION_NAME_UPLOAD).ResourceType(resourceType).BuildUrl(); + } + + private string GetRenameUrl(RenameParams parameters) => + Api + .ApiUrlImgUpV + .ResourceType(ApiShared.GetCloudinaryParam(parameters.ResourceType)) + .Action("rename") + .BuildUrl(); + + private string CheckUploadParametersAndGetUploadUrl(BasicRawUploadParams parameters) + { + if (parameters == null) + { + throw new ArgumentNullException(nameof(parameters), "Upload parameters should be defined"); + } + + string uri = GetApiUrlV() + .Action(Constants.ACTION_NAME_UPLOAD) + .ResourceType(ApiShared.GetCloudinaryParam(parameters.ResourceType)) + .BuildUrl(); + + parameters.File.Reset(); + return uri; + } + + /// + /// Uploads a resource to Cloudinary. + /// + /// Parameters of uploading . + /// Results of uploading. + private T Upload(TP parameters) + where T : UploadResult, new() + where TP : BasicRawUploadParams, new() + { + return UploadAsync(parameters, null).GetAwaiter().GetResult(); + } + + /// + /// Uploads a resource to Cloudinary asynchronously. + /// + /// Parameters of uploading . + /// (Optional) Cancellation token. + /// Results of uploading. + private Task UploadAsync(BasicRawUploadParams parameters, CancellationToken? cancellationToken = null) + where T : UploadResult, new() + { + var uri = CheckUploadParametersAndGetUploadUrl(parameters); + + return CallUploadApiAsync( + HttpMethod.POST, + uri, + parameters, + cancellationToken, + parameters.File, + null); + } + + private string GetDownloadUrl(UrlBuilder builder, IDictionary parameters) + { + Api.FinalizeUploadParameters(parameters); + builder.SetParameters(parameters); + return builder.ToString(); + } + + /// + /// Get default API URL with version. + /// + /// URL of the API. + private Url GetApiUrlV() + { + return Api.ApiUrlV; + } + + /// + /// Upload large file parameters. + /// + internal class UploadLargeParams + { + /// + /// Initializes a new instance of the class. + /// + /// Basic raw upload parameters. + /// Buffer size. + /// Technological layer to work with cloudinary API. + public UploadLargeParams(BasicRawUploadParams parameters, int bufferSize, Api api) + { + parameters.File.Reset(bufferSize); + this.Parameters = parameters; + this.Url = GetUploadUrl(parameters, api); + this.BufferSize = bufferSize; + } + + /// + /// Gets buffer size. + /// + public int BufferSize { get; } + + /// + /// Gets url. + /// + public string Url { get; } + + /// + /// Gets basic raw upload parameters. + /// + public BasicRawUploadParams Parameters { get; } + + /// + /// Gets request headers. + /// + public Dictionary Headers { get; } = new Dictionary + { + ["X-Unique-Upload-Id"] = RandomPublicId(), + }; + + /// + /// Generate random PublicId. + /// + /// Randomly generated PublicId. + private static string RandomPublicId() + { + var buffer = new byte[8]; + new Random().NextBytes(buffer); + return string.Concat(buffer.Select(x => x.ToString("X2", CultureInfo.InvariantCulture)).ToArray()); + } + + /// + /// A convenient method for uploading an image before testing. + /// + /// Parameters of type BasicRawUploadParams. + /// Action to set custom upload parameters. + /// The upload url. + private static string GetUploadUrl(BasicRawUploadParams parameters, Api mApi) + { + var url = mApi.ApiUrlImgUpV; + var name = Enum.GetName(typeof(ResourceType), parameters.ResourceType); + if (name != null) + { + url.ResourceType(name.ToLowerInvariant()); + } + + return url.BuildUrl(); + } + } + } +} diff --git a/CloudinaryDotNet/Api/ICloudinaryAdmin.cs b/CloudinaryDotNet/Api/ICloudinaryAdmin.cs new file mode 100644 index 00000000..e78e657f --- /dev/null +++ b/CloudinaryDotNet/Api/ICloudinaryAdmin.cs @@ -0,0 +1,1311 @@ +namespace CloudinaryDotNet +{ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using CloudinaryDotNet.Actions; + + /// + /// Main class of Cloudinary .NET Admin API. + /// + public interface ICloudinaryAdmin + { + /// + /// Gets the advanced search provider used by the Cloudinary instance. + /// + /// Instance of the class. + Search Search(); + + /// + /// Lists resource types asynchronously. + /// + /// (Optional) Cancellation token. + /// Parsed list of resource types. + Task ListResourceTypesAsync(CancellationToken? cancellationToken = null); + + /// + /// Lists resource types. + /// + /// Parsed list of resource types. + ListResourceTypesResult ListResourceTypes(); + + /// + /// Lists resources asynchronously asynchronously. + /// + /// Starting position. + /// Whether to include tags in result. + /// Whether to include context in result. + /// Whether to include moderation status in result. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesAsync( + string nextCursor = null, + bool tags = true, + bool context = true, + bool moderations = true, + CancellationToken? cancellationToken = null); + + /// + /// Gets a list of resources asynchronously. + /// + /// Parameters to list resources. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesAsync(ListResourcesParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Lists resources. + /// + /// Starting position. + /// Whether to include tags in result. + /// Whether to include context in result. + /// Whether to include moderation status in result. + /// Parsed result of the resources listing. + ListResourcesResult ListResources( + string nextCursor = null, + bool tags = true, + bool context = true, + bool moderations = true); + + /// + /// Gets a list of resources. + /// + /// Parameters to list resources. + /// Parsed result of the resources listing. + ListResourcesResult ListResources(ListResourcesParams parameters); + + /// + /// Lists resources of specified type asynchronously. + /// + /// Resource type. + /// Starting position. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesByTypeAsync( + string type, + string nextCursor = null, + CancellationToken? cancellationToken = null); + + /// + /// Lists resources of specified type. + /// + /// Resource type. + /// Starting position. + /// Parsed result of the resources listing. + ListResourcesResult ListResourcesByType(string type, string nextCursor = null); + + /// + /// Lists resources by prefix asynchronously. + /// + /// Public identifier prefix. + /// Resource type. + /// Starting position. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesByPrefixAsync( + string prefix, + string type = "upload", + string nextCursor = null, + CancellationToken? cancellationToken = null); + + /// + /// Lists resources by prefix asynchronously. + /// + /// Public identifier prefix. + /// Whether to include tags in result. + /// Whether to include context in result. + /// If true, include moderation status for each resource. + /// Resource type. + /// Starting position. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesByPrefixAsync( + string prefix, + bool tags, + bool context, + bool moderations, + string type = "upload", + string nextCursor = null, + CancellationToken? cancellationToken = null); + + /// + /// Lists resources by prefix. + /// + /// Public identifier prefix. + /// Resource type. + /// Starting position. + /// Parsed result of the resources listing. + ListResourcesResult ListResourcesByPrefix( + string prefix, + string type = "upload", + string nextCursor = null); + + /// + /// Lists resources by prefix. + /// + /// Public identifier prefix. + /// Whether to include tags in result. + /// Whether to include context in result. + /// If true, include moderation status for each resource. + /// Resource type. + /// Starting position. + /// Parsed result of the resources listing. + ListResourcesResult ListResourcesByPrefix(string prefix, bool tags, bool context, bool moderations, string type = "upload", string nextCursor = null); + + /// + /// Lists resources by tag asynchronously. + /// + /// The tag. + /// Starting position. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesByTagAsync( + string tag, + string nextCursor = null, + CancellationToken? cancellationToken = null); + + /// + /// Lists resources by tag. + /// + /// The tag. + /// Starting position. + /// Parsed result of the resources listing. + ListResourcesResult ListResourcesByTag(string tag, string nextCursor = null); + + /// + /// Returns resources with specified public identifiers asynchronously. + /// + /// Public identifiers. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesByPublicIdsAsync( + IEnumerable publicIds, + CancellationToken? cancellationToken = null); + + /// + /// Returns resources with specified public identifiers. + /// + /// Public identifiers. + /// Parsed result of the resources listing. + ListResourcesResult ListResourcesByPublicIds(IEnumerable publicIds); + + /// + /// Returns resources with specified public identifiers asynchronously. + /// + /// Public identifiers. + /// Whether to include tags in result. + /// Whether to include context in result. + /// Whether to include moderation status in result. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourceByPublicIdsAsync( + IEnumerable publicIds, + bool tags, + bool context, + bool moderations, + CancellationToken? cancellationToken = null); + + /// + /// Returns resources with specified public identifiers. + /// + /// Public identifiers. + /// Whether to include tags in result. + /// Whether to include context in result. + /// Whether to include moderation status in result. + /// Parsed result of the resources listing. + ListResourcesResult ListResourceByPublicIds(IEnumerable publicIds, bool tags, bool context, bool moderations); + + /// + /// Lists resources by moderation status asynchronously. + /// + /// The moderation kind. + /// The moderation status. + /// Whether to include tags in result. + /// Whether to include context in result. + /// Whether to include moderation status in result. + /// The next cursor. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesByModerationStatusAsync( + string kind, + ModerationStatus status, + bool tags = true, + bool context = true, + bool moderations = true, + string nextCursor = null, + CancellationToken? cancellationToken = null); + + /// + /// Lists resources by moderation status. + /// + /// The moderation kind. + /// The moderation status. + /// Whether to include tags in result. + /// Whether to include context in result. + /// Whether to include moderation status in result. + /// The next cursor. + /// Parsed result of the resources listing. + ListResourcesResult ListResourcesByModerationStatus( + string kind, + ModerationStatus status, + bool tags = true, + bool context = true, + bool moderations = true, + string nextCursor = null); + + /// + /// List resources by context metadata keys and values asynchronously. + /// + /// Only resources with the given key should be returned. + /// When provided should only return resources with this given value for the context key. + /// When not provided, return all resources for which the context key exists. + /// If true, include list of tag names assigned for each resource. + /// If true, include context assigned to each resource. + /// The next cursor. + /// (Optional) Cancellation token. + /// Parsed result of the resources listing. + Task ListResourcesByContextAsync( + string key, + string value = "", + bool tags = false, + bool context = false, + string nextCursor = null, + CancellationToken? cancellationToken = null); + + /// + /// List resources by context metadata keys and values. + /// + /// Only resources with the given key should be returned. + /// When provided should only return resources with this given value for the context key. + /// When not provided, return all resources for which the context key exists. + /// If true, include list of tag names assigned for each resource. + /// If true, include context assigned to each resource. + /// The next cursor. + /// Parsed result of the resources listing. + ListResourcesResult ListResourcesByContext( + string key, + string value = "", + bool tags = false, + bool context = false, + string nextCursor = null); + + /// + /// Publishes resources by prefix asynchronously. + /// + /// The prefix for publishing resources. + /// Parameters for publishing of resources. + /// Cancellation token. + /// Parsed result of publishing. + Task PublishResourceByPrefixAsync( + string prefix, + PublishResourceParams parameters, + CancellationToken? cancellationToken); + + /// + /// Publishes resources by prefix. + /// + /// The prefix for publishing resources. + /// Parameters for publishing of resources. + /// Parsed result of publishing. + PublishResourceResult PublishResourceByPrefix(string prefix, PublishResourceParams parameters); + + /// + /// Publishes resources by tag asynchronously. + /// + /// All resources with the given tag will be published. + /// Parameters for publishing of resources. + /// (Optional) Cancellation token. + /// Parsed result of publishing. + Task PublishResourceByTagAsync( + string tag, + PublishResourceParams parameters, + CancellationToken? cancellationToken = null); + + /// + /// Publishes resources by tag. + /// + /// All resources with the given tag will be published. + /// Parameters for publishing of resources. + /// Parsed result of publishing. + PublishResourceResult PublishResourceByTag(string tag, PublishResourceParams parameters); + + /// + /// Publishes resource by Id asynchronously. + /// + /// Not used. + /// Parameters for publishing of resources. + /// Cancellation token. + /// Structure with the results of publishing. + Task PublishResourceByIdsAsync( + string tag, + PublishResourceParams parameters, + CancellationToken? cancellationToken); + + /// + /// Publishes resource by Id. + /// + /// Not used. + /// Parameters for publishing of resources. + /// Structure with the results of publishing. + PublishResourceResult PublishResourceByIds(string tag, PublishResourceParams parameters); + + /// + /// Updates access mode for the resources selected by tag asynchronously. + /// + /// Update all resources with the given tag (up to a maximum + /// of 100 matching original resources). + /// Parameters for updating of resources. + /// (Optional) Cancellation token. + /// Structure with the results of update. + Task UpdateResourceAccessModeByTagAsync( + string tag, + UpdateResourceAccessModeParams parameters, + CancellationToken? cancellationToken = null); + + /// + /// Updates access mode for the resources selected by tag. + /// + /// Update all resources with the given tag (up to a maximum + /// of 100 matching original resources). + /// Parameters for updating of resources. + /// Structure with the results of update. + UpdateResourceAccessModeResult UpdateResourceAccessModeByTag(string tag, UpdateResourceAccessModeParams parameters); + + /// + /// Updates access mode for the resources selected by prefix asynchronously. + /// + /// Update all resources where the public ID starts with the given prefix (up to a maximum + /// of 100 matching original resources). + /// Parameters for updating of resources. + /// (Optional) Cancellation token. + /// Structure with the results of update. + Task UpdateResourceAccessModeByPrefixAsync( + string prefix, + UpdateResourceAccessModeParams parameters, + CancellationToken? cancellationToken = null); + + /// + /// Updates access mode for the resources selected by prefix. + /// + /// Update all resources where the public ID starts with the given prefix (up to a maximum + /// of 100 matching original resources). + /// Parameters for updating of resources. + /// Structure with the results of update. + UpdateResourceAccessModeResult UpdateResourceAccessModeByPrefix( + string prefix, + UpdateResourceAccessModeParams parameters); + + /// + /// Updates access mode for the resources selected by public ids asynchronously. + /// + /// Parameters for updating of resources. Update all resources with the given + /// public IDs (array of up to 100 public_ids). + /// (Optional) Cancellation token. + /// Structure with the results of update. + Task UpdateResourceAccessModeByIdsAsync( + UpdateResourceAccessModeParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Updates access mode for the resources selected by public ids. + /// + /// Parameters for updating of resources. Update all resources with the given + /// public IDs (array of up to 100 public_ids). + /// Structure with the results of update. + UpdateResourceAccessModeResult UpdateResourceAccessModeByIds(UpdateResourceAccessModeParams parameters); + + /// + /// Deletes derived resources by the given transformation (should be specified in parameters) asynchronously. + /// + /// Parameters to delete derived resources. + /// (Optional) Cancellation token. + /// Parsed result of deletion derived resources. + Task DeleteDerivedResourcesByTransformAsync(DelDerivedResParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Deletes derived resources by the given transformation (should be specified in parameters). + /// + /// Parameters to delete derived resources. + /// Parsed result of deletion derived resources. + DelDerivedResResult DeleteDerivedResourcesByTransform(DelDerivedResParams parameters); + + /// + /// Async call to get a list of folders in the root asynchronously. + /// + /// (optional) Parameters for managing folders list. + /// (Optional) Cancellation token. + /// Parsed result of folders listing. + Task RootFoldersAsync(GetFoldersParams parameters = null, CancellationToken? cancellationToken = null); + + /// + /// Gets a list of folders in the root. + /// + /// (optional) Parameters for managing folders list. + /// Parsed result of folders listing. + GetFoldersResult RootFolders(GetFoldersParams parameters = null); + + /// + /// Gets a list of subfolders in a specified folder asynchronously. + /// + /// The folder name. + /// (Optional) Cancellation token. + /// Parsed result of folders listing. + Task SubFoldersAsync(string folder, CancellationToken? cancellationToken = null); + + /// + /// Gets a list of subfolders in a specified folder asynchronously. + /// + /// The folder name. + /// (Optional) Parameters for managing folders list. + /// (Optional) Cancellation token. + /// Parsed result of folders listing. + Task SubFoldersAsync(string folder, GetFoldersParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Gets a list of subfolders in a specified folder. + /// + /// The folder name. + /// (Optional) Parameters for managing folders list. + /// Parsed result of folders listing. + GetFoldersResult SubFolders(string folder, GetFoldersParams parameters = null); + + /// + /// Deletes folder asynchronously. + /// + /// Folder name. + /// (Optional) Cancellation token. + /// Parsed result of folder deletion. + Task DeleteFolderAsync(string folder, CancellationToken? cancellationToken = null); + + /// + /// Deletes folder. + /// + /// Folder name. + /// Parsed result of folder deletion. + DeleteFolderResult DeleteFolder(string folder); + + /// + /// Create a new empty folder. + /// + /// The full path of the new folder to create. + /// Parsed result of folder creation. + CreateFolderResult CreateFolder(string folder); + + /// + /// Create a new empty folder. + /// + /// The full path of the new folder to create. + /// (Optional) Cancellation token. + /// Parsed result of folder creation. + Task CreateFolderAsync(string folder, CancellationToken? cancellationToken = null); + + /// + /// Creates the upload preset. + /// Upload presets allow you to define the default behavior for your uploads, instead of + /// receiving these as parameters during the upload request itself. Upload presets have + /// precedence over client-side upload parameters asynchronously. + /// + /// Parameters of the upload preset. + /// (Optional) Cancellation token. + /// Parsed response after manipulation of upload presets. + Task CreateUploadPresetAsync(UploadPresetParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Creates the upload preset. + /// Upload presets allow you to define the default behavior for your uploads, instead of receiving these as parameters during the upload request itself. Upload presets have precedence over client-side upload parameters. + /// + /// Parameters of the upload preset. + /// Parsed response after manipulation of upload presets. + UploadPresetResult CreateUploadPreset(UploadPresetParams parameters); + + /// + /// Updates the upload preset. + /// Every update overwrites all the preset settings asynchronously. + /// File specified as null because it's non-uploading action. + /// + /// New parameters for upload preset. + /// (Optional) Cancellation token. + /// Parsed response after manipulation of upload presets. + Task UpdateUploadPresetAsync(UploadPresetParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Updates the upload preset. + /// Every update overwrites all the preset settings. + /// File specified as null because it's non-uploading action. + /// + /// New parameters for upload preset. + /// Parsed response after manipulation of upload presets. + UploadPresetResult UpdateUploadPreset(UploadPresetParams parameters); + + /// + /// Gets the upload preset asynchronously. + /// + /// Name of the upload preset. + /// (Optional) Cancellation token. + /// Upload preset details. + Task GetUploadPresetAsync(string name, CancellationToken? cancellationToken = null); + + /// + /// Gets the upload preset. + /// + /// Name of the upload preset. + /// Upload preset details. + GetUploadPresetResult GetUploadPreset(string name); + + /// + /// Lists upload presets asynchronously. + /// + /// Next cursor. + /// (Optional) Cancellation token. + /// Parsed result of upload presets listing. + Task ListUploadPresetsAsync(string nextCursor = null, CancellationToken? cancellationToken = null); + + /// + /// Lists upload presets asynchronously. + /// + /// Parameters to list upload presets. + /// (Optional) Cancellation token. + /// Parsed result of upload presets listing. + Task ListUploadPresetsAsync(ListUploadPresetsParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Lists upload presets. + /// + /// (Optional) Starting position. + /// Parsed result of upload presets listing. + ListUploadPresetsResult ListUploadPresets(string nextCursor = null); + + /// + /// Lists upload presets. + /// + /// Parameters to list upload presets. + /// Parsed result of upload presets listing. + ListUploadPresetsResult ListUploadPresets(ListUploadPresetsParams parameters); + + /// + /// Deletes the upload preset asynchronously. + /// + /// Name of the upload preset. + /// (Optional) Cancellation token. + /// Result of upload preset deletion. + Task DeleteUploadPresetAsync(string name, CancellationToken? cancellationToken = null); + + /// + /// Deletes the upload preset. + /// + /// Name of the upload preset. + /// Result of upload preset deletion. + DeleteUploadPresetResult DeleteUploadPreset(string name); + + /// + /// Gets the Cloudinary account usage details asynchronously. + /// + /// (Optional) The date for the usage report. Must be within the last 3 months. + /// (Optional) Cancellation token. + /// The report on the status of your Cloudinary account usage details. + Task GetUsageAsync(DateTime? date, CancellationToken? cancellationToken = null); + + /// + /// Gets the Cloudinary account usage details asynchronously. + /// + /// (Optional) Cancellation token. + /// The report on the status of your Cloudinary account usage details. + Task GetUsageAsync(CancellationToken? cancellationToken = null); + + /// + /// Gets the Cloudinary account usage details. + /// + /// (Optional) The date for the usage report. Must be within the last 3 months. + /// The report on the status of your Cloudinary account usage details. + UsageResult GetUsage(DateTime? date = null); + + /// + /// Gets a list of tags asynchronously. + /// + /// (Optional) Cancellation token. + /// Parsed list of tags. + Task ListTagsAsync(CancellationToken? cancellationToken = null); + + /// + /// Gets a list of tags asynchronously. + /// + /// Parameters of the request. + /// (Optional) Cancellation token. + /// Parsed list of tags. + Task ListTagsAsync(ListTagsParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Gets a list of all tags. + /// + /// Parsed list of tags. + ListTagsResult ListTags(); + + /// + /// Gets a list of tags. + /// + /// Parameters of the request. + /// Parsed list of tags. + ListTagsResult ListTags(ListTagsParams parameters); + + /// + /// Finds all tags that start with the given prefix asynchronously. + /// + /// The tag prefix. + /// (Optional) Cancellation token. + /// Parsed list of tags. + Task ListTagsByPrefixAsync(string prefix, CancellationToken? cancellationToken = null); + + /// + /// Finds all tags that start with the given prefix. + /// + /// The tag prefix. + /// Parsed list of tags. + ListTagsResult ListTagsByPrefix(string prefix); + + /// + /// Gets a list of transformations asynchronously. + /// + /// (Optional) Cancellation token. + /// Parsed list of transformations details. + Task ListTransformationsAsync(CancellationToken? cancellationToken = null); + + /// + /// Gets a list of transformations asynchronously. + /// + /// Parameters of the request for a list of transformation. + /// (Optional) Cancellation token. + /// Parsed list of transformations details. + Task ListTransformationsAsync(ListTransformsParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Gets a list of transformations. + /// + /// Parsed list of transformations details. + ListTransformsResult ListTransformations(); + + /// + /// Gets a list of transformations. + /// + /// Parameters of the request for a list of transformation. + /// Parsed list of transformations details. + ListTransformsResult ListTransformations(ListTransformsParams parameters); + + /// + /// Gets details of a single transformation asynchronously. + /// + /// Name of the transformation. + /// (Optional) Cancellation token. + /// Parsed details of a single transformation. + Task GetTransformAsync(string transform, CancellationToken? cancellationToken = null); + + /// + /// Gets details of a single transformation asynchronously. + /// + /// Parameters of the request of transformation details. + /// (Optional) Cancellation token. + /// Parsed details of a single transformation. + Task GetTransformAsync(GetTransformParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Gets details of a single transformation by name. + /// + /// Name of the transformation. + /// Parsed details of a single transformation. + GetTransformResult GetTransform(string transform); + + /// + /// Gets details of a single transformation. + /// + /// Parameters of the request of transformation details. + /// Parsed details of a single transformation. + GetTransformResult GetTransform(GetTransformParams parameters); + + /// + /// Updates details of an existing resource asynchronously. + /// + /// The public ID of the resource to update. + /// The image moderation status. + /// (Optional) Cancellation token. + /// Parsed response of the detailed resource information. + Task UpdateResourceAsync(string publicId, ModerationStatus moderationStatus, CancellationToken? cancellationToken = null); + + /// + /// Updates details of an existing resource asynchronously. + /// + /// Parameters to update details of an existing resource. + /// (Optional) Cancellation token. + /// Parsed response of the detailed resource information. + Task UpdateResourceAsync(UpdateParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Updates details of an existing resource. + /// + /// The public ID of the resource to update. + /// The image moderation status. + /// Parsed response of the detailed resource information. + GetResourceResult UpdateResource(string publicId, ModerationStatus moderationStatus); + + /// + /// Updates details of an existing resource. + /// + /// Parameters to update details of an existing resource. + /// Parsed response of the detailed resource information. + GetResourceResult UpdateResource(UpdateParams parameters); + + /// + /// Gets details of a single resource as well as all its derived resources by its public ID asynchronously. + /// + /// The public ID of the resource. + /// (Optional) Cancellation token. + /// Parsed response with the detailed resource information. + Task GetResourceAsync(string publicId, CancellationToken? cancellationToken = null); + + /// + /// Gets details of the requested resource as well as all its derived resources asynchronously. + /// + /// Parameters of the request of resource. + /// (Optional) Cancellation token. + /// Parsed response with the detailed resource information. + Task GetResourceAsync(GetResourceParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Gets details of a single resource as well as all its derived resources by its public ID. + /// + /// The public ID of the resource. + /// Parsed response with the detailed resource information. + GetResourceResult GetResource(string publicId); + + /// + /// Gets details of the requested resource as well as all its derived resources. + /// + /// Parameters of the request of resource. + /// Parsed response with the detailed resource information. + GetResourceResult GetResource(GetResourceParams parameters); + + /// + /// Deletes all derived resources with the given IDs asynchronously. + /// + /// An array of up to 100 derived_resource_ids. + /// Parsed result of deletion derived resources. + Task DeleteDerivedResourcesAsync(params string[] ids); + + /// + /// Deletes all derived resources with the given parameters asynchronously. + /// + /// Parameters to delete derived resources. + /// (Optional) Cancellation token. + /// Parsed result of deletion derived resources. + Task DeleteDerivedResourcesAsync(DelDerivedResParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Deletes all derived resources with the given IDs. + /// + /// An array of up to 100 derived_resource_ids. + /// Parsed result of deletion derived resources. + DelDerivedResResult DeleteDerivedResources(params string[] ids); + + /// + /// Deletes all derived resources with the given parameters. + /// + /// Parameters to delete derived resources. + /// Parsed result of deletion derived resources. + DelDerivedResResult DeleteDerivedResources(DelDerivedResParams parameters); + + /// + /// Deletes all resources of the given resource type and with the given public IDs asynchronously. + /// + /// The type of file to delete. Default: image. + /// Array of up to 100 public_ids. + /// Parsed result of deletion resources. + Task DeleteResourcesAsync(ResourceType type, params string[] publicIds); + + /// + /// Deletes all resources with the given public IDs asynchronously. + /// + /// Array of up to 100 public_ids. + /// Parsed result of deletion resources. + Task DeleteResourcesAsync(params string[] publicIds); + + /// + /// Deletes all resources with parameters asynchronously. + /// + /// Parameters for deletion resources. + /// (Optional) Cancellation token. + /// Parsed result of deletion resources. + Task DeleteResourcesAsync(DelResParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Deletes all resources of the given resource type and with the given public IDs. + /// + /// The type of file to delete. Default: image. + /// Array of up to 100 public_ids. + /// Parsed result of deletion resources. + DelResResult DeleteResources(ResourceType type, params string[] publicIds); + + /// + /// Deletes all resources with the given public IDs. + /// + /// Array of up to 100 public_ids. + /// Parsed result of deletion resources. + DelResResult DeleteResources(params string[] publicIds); + + /// + /// Deletes all resources with parameters. + /// + /// Parameters for deletion resources. + /// Parsed result of deletion resources. + DelResResult DeleteResources(DelResParams parameters); + + /// + /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to + /// a maximum of 1000 original resources) asynchronously. + /// + /// Delete all resources where the public ID starts with the given prefix. + /// (Optional) Cancellation token. + /// Parsed result of deletion resources. + Task DeleteResourcesByPrefixAsync(string prefix, CancellationToken? cancellationToken = null); + + /// + /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to + /// a maximum of 1000 original resources) asynchronously. + /// + /// Delete all resources where the public ID starts with the given prefix. + /// If true, delete only the derived images of the matching resources. + /// Continue deletion from the given cursor. + /// (Optional) Cancellation token. + /// Parsed result of deletion resources. + Task DeleteResourcesByPrefixAsync(string prefix, bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null); + + /// + /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to + /// a maximum of 1000 original resources). + /// + /// Delete all resources where the public ID starts with the given prefix. + /// Parsed result of deletion resources. + DelResResult DeleteResourcesByPrefix(string prefix); + + /// + /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to + /// a maximum of 1000 original resources). + /// + /// Delete all resources where the public ID starts with the given prefix. + /// If true, delete only the derived images of the matching resources. + /// Continue deletion from the given cursor. + /// Parsed result of deletion resources. + DelResResult DeleteResourcesByPrefix(string prefix, bool keepOriginal, string nextCursor); + + /// + /// Deletes resources by the given tag name asynchronously. + /// + /// + /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of + /// 1000 original resources). + /// + /// (Optional) Cancellation token. + /// Parsed result of deletion resources. + Task DeleteResourcesByTagAsync(string tag, CancellationToken? cancellationToken = null); + + /// + /// Deletes resources by the given tag name asynchronously. + /// + /// + /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of + /// 1000 original resources). + /// + /// If true, delete only the derived images of the matching resources. + /// Continue deletion from the given cursor. + /// (Optional) Cancellation token. + /// Parsed result of deletion resources. + Task DeleteResourcesByTagAsync(string tag, bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null); + + /// + /// Deletes resources by the given tag name. + /// + /// + /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of + /// 1000 original resources). + /// + /// Parsed result of deletion resources. + DelResResult DeleteResourcesByTag(string tag); + + /// + /// Deletes resources by the given tag name. + /// + /// + /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of + /// 1000 original resources). + /// + /// If true, delete only the derived images of the matching resources. + /// Continue deletion from the given cursor. + /// Parsed result of deletion resources. + DelResResult DeleteResourcesByTag(string tag, bool keepOriginal, string nextCursor); + + /// + /// Deletes all resources asynchronously. + /// + /// (Optional) Cancellation token. + /// Parsed result of deletion resources. + Task DeleteAllResourcesAsync(CancellationToken? cancellationToken = null); + + /// + /// Deletes all resources with conditions asynchronously. + /// + /// If true, delete only the derived resources. + /// + /// Value of the to continue delete from. + /// + /// (Optional) Cancellation token. + /// Parsed result of deletion resources. + Task DeleteAllResourcesAsync(bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null); + + /// + /// Deletes all resources. + /// + /// Parsed result of deletion resources. + DelResResult DeleteAllResources(); + + /// + /// Deletes all resources with conditions. + /// + /// If true, delete only the derived resources. + /// + /// Value of the to continue delete from. + /// + /// Parsed result of deletion resources. + DelResResult DeleteAllResources(bool keepOriginal, string nextCursor); + + /// + /// Restores a deleted resources by array of public ids asynchronously. + /// + /// The public IDs of (deleted or existing) backed up resources to restore. + /// Parsed result of restoring resources. + Task RestoreAsync(params string[] publicIds); + + /// + /// Restores a deleted resources asynchronously. + /// + /// Parameters to restore a deleted resources. + /// (Optional) Cancellation token. + /// Parsed result of restoring resources. + Task RestoreAsync(RestoreParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Restores a deleted resources by array of public ids. + /// + /// The public IDs of (deleted or existing) backed up resources to restore. + /// Parsed result of restoring resources. + RestoreResult Restore(params string[] publicIds); + + /// + /// Restores a deleted resources. + /// + /// Parameters to restore a deleted resources. + /// Parsed result of restoring resources. + RestoreResult Restore(RestoreParams parameters); + + /// + /// Returns list of all upload mappings asynchronously. + /// + /// + /// Uses only and + /// properties. Can be null. + /// + /// (Optional) Cancellation token. + /// Parsed response after Upload mappings manipulation. + Task UploadMappingsAsync(UploadMappingParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Returns list of all upload mappings. + /// + /// + /// Uses only and + /// properties. Can be null. + /// + /// Parsed response after Upload mappings manipulation. + UploadMappingResults UploadMappings(UploadMappingParams parameters); + + /// + /// Returns single upload mapping by name asynchronously. + /// + /// Folder name. + /// (Optional) Cancellation token. + /// Parsed response after Upload mappings manipulation. + Task UploadMappingAsync(string folder, CancellationToken? cancellationToken = null); + + /// + /// Returns single upload mapping by name. + /// + /// Folder name. + /// Parsed response after Upload mappings manipulation. + UploadMappingResults UploadMapping(string folder); + + /// + /// Creates a new upload mapping folder and its template (URL) asynchronously. + /// + /// Folder name to create. + /// URL template for mapping to the . + /// (Optional) Cancellation token. + /// Parsed response after Upload mappings manipulation. + Task CreateUploadMappingAsync(string folder, string template, CancellationToken? cancellationToken = null); + + /// + /// Creates a new upload mapping folder and its template (URL). + /// + /// Folder name to create. + /// URL template for mapping to the . + /// Parsed response after Upload mappings manipulation. + UploadMappingResults CreateUploadMapping(string folder, string template); + + /// + /// Updates existing upload mapping asynchronously. + /// + /// Existing Folder to be updated. + /// New value of Template URL. + /// (Optional) Cancellation token. + /// Parsed response after Upload mappings update. + Task UpdateUploadMappingAsync(string folder, string newTemplate, CancellationToken? cancellationToken = null); + + /// + /// Updates existing upload mapping. + /// + /// Existing Folder to be updated. + /// New value of Template URL. + /// Parsed response after Upload mappings update. + UploadMappingResults UpdateUploadMapping(string folder, string newTemplate); + + /// + /// Deletes all upload mappings asynchronously. + /// + /// (Optional) Cancellation token. + /// Parsed response after Upload mappings delete. + Task DeleteUploadMappingAsync(CancellationToken? cancellationToken = null); + + /// + /// Deletes upload mapping by name asynchronously. + /// + /// Folder name. + /// (Optional) Cancellation token. + /// Parsed response after Upload mappings manipulation. + Task DeleteUploadMappingAsync(string folder, CancellationToken? cancellationToken = null); + + /// + /// Deletes all upload mappings. + /// + /// Parsed response after Upload mappings delete. + UploadMappingResults DeleteUploadMapping(); + + /// + /// Deletes upload mapping by name. + /// + /// Folder name. + /// Parsed response after Upload mappings manipulation. + UploadMappingResults DeleteUploadMapping(string folder); + + /// + /// Updates Cloudinary transformation resource asynchronously. + /// + /// Parameters for transformation update. + /// (Optional) Cancellation token. + /// Parsed response after transformation manipulation. + Task UpdateTransformAsync(UpdateTransformParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Updates Cloudinary transformation resource. + /// + /// Parameters for transformation update. + /// Parsed response after transformation manipulation. + UpdateTransformResult UpdateTransform(UpdateTransformParams parameters); + + /// + /// Creates Cloudinary transformation resource asynchronously. + /// + /// Parameters of the new transformation. + /// (Optional) Cancellation token. + /// Parsed response after transformation manipulation. + Task CreateTransformAsync(CreateTransformParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Creates Cloudinary transformation resource. + /// + /// Parameters of the new transformation. + /// Parsed response after transformation manipulation. + TransformResult CreateTransform(CreateTransformParams parameters); + + /// + /// Deletes transformation by name asynchronously. + /// + /// The name of transformation to delete. + /// (Optional) Cancellation token. + /// Parsed response after transformation manipulation. + Task DeleteTransformAsync(string transformName, CancellationToken? cancellationToken = null); + + /// + /// Deletes transformation by name. + /// + /// The name of transformation to delete. + /// Parsed response after transformation manipulation. + TransformResult DeleteTransform(string transformName); + + /// + /// Create a new metadata field definition. + /// + /// Parameters of the metadata field. + /// Parsed result of the metadata field creating. + /// Type of the metadata field. + MetadataFieldResult AddMetadataField(MetadataFieldCreateParams parameters); + + /// + /// Retrieve a list of all metadata field definitions as an array of JSON objects. + /// + /// Parsed list of metadata field definitions. + MetadataFieldListResult ListMetadataFields(); + + /// + /// Retrieve a single metadata field definition. + /// + /// The ID of the metadata field. + /// Parsed information about metadata field. + MetadataFieldResult GetMetadataField(string fieldExternalId); + + /// + /// Update a metadata field by its external ID. + /// There is no need to pass the entire object, only properties to be updated. + /// + /// The ID of the metadata field. + /// Parameters of the metadata field to be updated. + /// Parsed result of the operation. + /// Type of the metadata field. + MetadataFieldResult UpdateMetadataField(string fieldExternalId, MetadataFieldUpdateParams parameters); + + /// + /// Update the datasource of a supported field type (currently only enum and set). + /// The update is partial: datasource entries with an existing external_id will be updated. + /// Entries with new external_id�s (or without external_id�s) will be appended. + /// + /// The ID of the metadata field. + /// Parameters of the datasource to be updated. + /// Parsed result of the operation. + MetadataDataSourceResult UpdateMetadataDataSourceEntries(string fieldExternalId, MetadataDataSourceParams parameters); + + /// + /// Delete a metadata field definition. + /// The field should no longer be considered a valid candidate for all other endpoints. + /// + /// The ID of the metadata field. + /// Parsed result of the operation. + DelMetadataFieldResult DeleteMetadataField(string fieldExternalId); + + /// + /// Delete datasource entries for a specified metadata field definition. + /// This operation sets the state of the entries to inactive. + /// + /// The ID of the metadata field. + /// An array of IDs of datasource entries to delete. + /// Parsed result of the operation. + MetadataDataSourceResult DeleteMetadataDataSourceEntries(string fieldExternalId, List entriesExternalIds); + + /// + /// Restore (unblock) any previously deleted datasource entries for a specified metadata field definition + /// and set the state of the entries to active. + /// + /// The ID of the metadata field. + /// An array of IDs of datasource entries to restore. + /// Parsed result of the operation. + MetadataDataSourceResult RestoreMetadataDataSourceEntries(string fieldExternalId, List entriesExternalIds); + + /// + /// Populate metadata fields with the given values. Existing values will be overwritten. + /// + /// Any metadata-value pairs given are merged with any existing metadata-value pairs + /// (an empty value for an existing metadata field clears the value). + /// + /// Values to be applied to metadata fields of uploaded assets. + /// Parsed result of the operation. + MetadataUpdateResult UpdateMetadata(MetadataUpdateParams parameters); + + /// + /// Create a new streaming profile asynchronously. + /// + /// Parameters of streaming profile creating. + /// (Optional) Cancellation token. + /// Detailed information about created streaming profile. + Task CreateStreamingProfileAsync(StreamingProfileCreateParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Create a new streaming profile. + /// + /// Parameters of streaming profile creating. + /// Detailed information about created streaming profile. + StreamingProfileResult CreateStreamingProfile(StreamingProfileCreateParams parameters); + + /// + /// Update streaming profile asynchronously. + /// + /// Name to be assigned to a streaming profile. + /// Parameters of streaming profile updating. + /// (Optional) Cancellation token. + /// parameters can't be null. + /// name can't be null or empty. + /// Result of updating the streaming profile. + Task UpdateStreamingProfileAsync( + string name, + StreamingProfileUpdateParams parameters, + CancellationToken? cancellationToken = null); + + /// + /// Update streaming profile. + /// + /// Name to be assigned to a streaming profile. + /// Parameters of streaming profile updating. + /// both arguments can't be null. + /// Result of updating the streaming profile. + StreamingProfileResult UpdateStreamingProfile(string name, StreamingProfileUpdateParams parameters); + + /// + /// Delete streaming profile asynchronously. + /// + /// The Name of streaming profile. + /// (Optional) Cancellation token. + /// name can't be null. + /// Result of removing the streaming profile. + Task DeleteStreamingProfileAsync(string name, CancellationToken? cancellationToken = null); + + /// + /// Delete streaming profile. + /// + /// Streaming profile name to delete. + /// name can't be null. + /// Result of removing the streaming profile. + StreamingProfileResult DeleteStreamingProfile(string name); + + /// + /// Retrieve the details of a single streaming profile by name asynchronously. + /// + /// The Name of streaming profile. + /// (Optional) Cancellation token. + /// name can't be null. + /// Detailed information about the streaming profile. + Task GetStreamingProfileAsync(string name, CancellationToken? cancellationToken = null); + + /// + /// Retrieve the details of a single streaming profile by name. + /// + /// Streaming profile name. + /// name can't be null. + /// Detailed information about the streaming profile. + StreamingProfileResult GetStreamingProfile(string name); + + /// + /// Retrieve the list of streaming profiles, including built-in and custom profiles asynchronously. + /// + /// (Optional) Cancellation token. + /// Detailed information about streaming profiles. + Task ListStreamingProfilesAsync(CancellationToken? cancellationToken = null); + + /// + /// Retrieve the list of streaming profiles, including built-in and custom profiles. + /// + /// Detailed information about streaming profiles. + StreamingProfileListResult ListStreamingProfiles(); + } +} \ No newline at end of file diff --git a/CloudinaryDotNet/Api/ICloudinaryUpload.cs b/CloudinaryDotNet/Api/ICloudinaryUpload.cs new file mode 100644 index 00000000..10149f27 --- /dev/null +++ b/CloudinaryDotNet/Api/ICloudinaryUpload.cs @@ -0,0 +1,499 @@ +namespace CloudinaryDotNet +{ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using CloudinaryDotNet.Actions; + + /// + /// Main class of Cloudinary .NET Upload API. + /// + public interface ICloudinaryUpload + { + /// + /// Uploads an image file to Cloudinary asynchronously. + /// + /// Parameters of image uploading . + /// (Optional) Cancellation token. + /// Results of image uploading. + Task UploadAsync(ImageUploadParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Uploads a video file to Cloudinary asynchronously. + /// + /// Parameters of video uploading. + /// (Optional) Cancellation token. + /// Results of video uploading. + Task UploadAsync(VideoUploadParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Uploads a file to Cloudinary asynchronously. + /// + /// Resource type ("image", "raw", "video", "auto"). + /// Upload parameters. + /// File description. + /// (Optional) Cancellation token. + /// Results of the raw file uploading. + Task UploadAsync( + string resourceType, + IDictionary parameters, + FileDescription fileDescription, + CancellationToken? cancellationToken = null); + + /// + /// Uploads a file to Cloudinary asynchronously. + /// + /// Parameters of file uploading. + /// The type ("raw" or "auto", last by default). + /// (Optional) Cancellation token. + /// Parsed result of the raw file uploading. + Task UploadAsync(RawUploadParams parameters, string type = "auto", CancellationToken? cancellationToken = null); + + /// + /// Uploads an image file to Cloudinary. + /// + /// Parameters of image uploading . + /// Results of image uploading. + ImageUploadResult Upload(ImageUploadParams parameters); + + /// + /// Uploads a video file to Cloudinary. + /// + /// Parameters of video uploading. + /// Results of video uploading. + VideoUploadResult Upload(VideoUploadParams parameters); + + /// + /// Uploads a file to Cloudinary. + /// + /// Resource type ("image", "raw", "video", "auto"). + /// Upload parameters. + /// File description. + /// Results of the raw file uploading. + RawUploadResult Upload(string resourceType, IDictionary parameters, FileDescription fileDescription); + + /// + /// Uploads a file to Cloudinary. + /// + /// Parameters of file uploading. + /// The type ("raw" or "auto", last by default). + /// Parsed result of the raw file uploading. + RawUploadResult Upload(RawUploadParams parameters, string type = "auto"); + + /// + /// Uploads large file by dividing it to chunks asynchronously. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// (Optional) Cancellation token. + /// Parsed result of the large file uploading. + /// + /// Please use BasicRawUploadParams class for large raw file uploading! + /// or + /// The UploadLargeRaw method is intended to be used for large local file uploading and can't be used for + /// remote file uploading. + /// + Task UploadLargeRawAsync( + BasicRawUploadParams parameters, + int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null); + + /// + /// Uploads large file to Cloudinary by dividing it to chunks. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// Parsed result of the large file uploading. + /// + /// Please use BasicRawUploadParams class for large raw file uploading! + /// or + /// The UploadLargeRaw method is intended to be used for large local file uploading and can't be used for remote file uploading. + /// + RawUploadResult UploadLargeRaw(BasicRawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE); + + /// + /// Uploads large raw file to Cloudinary by dividing it to chunks asynchronously. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// (Optional) Cancellation token. + /// Parsed result of uploading. + Task UploadLargeAsync( + RawUploadParams parameters, + int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null); + + /// + /// Uploads large image file to Cloudinary by dividing it to chunks asynchronously. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// (Optional) Cancellation token. + /// Parsed result of uploading. + Task UploadLargeAsync( + ImageUploadParams parameters, + int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null); + + /// + /// Uploads large video file to Cloudinary by dividing it to chunks asynchronously. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// (Optional) Cancellation token. + /// Parsed result of uploading. + Task UploadLargeAsync( + VideoUploadParams parameters, + int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null); + + /// + /// Uploads large resources to Cloudinary by dividing it to chunks asynchronously. + /// + /// The type of result of upload. + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// (Optional) Cancellation token. + /// Parsed result of uploading. + Task UploadLargeAsync( + BasicRawUploadParams parameters, + int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, + CancellationToken? cancellationToken = null) + where T : UploadResult, new(); + + /// + /// Uploads large raw file to Cloudinary by dividing it to chunks. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// Parsed result of uploading. + RawUploadResult UploadLarge(RawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE); + + /// + /// Uploads large image file to Cloudinary by dividing it to chunks. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// Parsed result of uploading. + ImageUploadResult UploadLarge(ImageUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE); + + /// + /// Uploads large video file to Cloudinary by dividing it to chunks. + /// + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// Parsed result of uploading. + VideoUploadResult UploadLarge(VideoUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE); + + /// + /// Uploads large resources to Cloudinary by dividing it to chunks. + /// + /// The type of result of upload. + /// Parameters of file uploading. + /// Chunk (buffer) size (20 MB by default). + /// Parsed result of uploading. + T UploadLarge(BasicRawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE) + where T : UploadResult, new(); + + /// + /// Changes public identifier of a file asynchronously. + /// + /// Old identifier. + /// New identifier. + /// Overwrite a file with the same identifier as new if such file exists. + /// (Optional) Cancellation token. + /// Result of resource renaming. + Task RenameAsync( + string fromPublicId, + string toPublicId, + bool overwrite = false, + CancellationToken? cancellationToken = null); + + /// + /// Changes public identifier of a file asynchronously. + /// + /// Operation parameters. + /// (Optional) Cancellation token. + /// Result of resource renaming. + Task RenameAsync(RenameParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Changes public identifier of a file. + /// + /// Old identifier. + /// New identifier. + /// Overwrite a file with the same identifier as new if such file exists. + /// Result of resource renaming. + RenameResult Rename(string fromPublicId, string toPublicId, bool overwrite = false); + + /// + /// Changes public identifier of a file. + /// + /// Operation parameters. + /// Result of resource renaming. + RenameResult Rename(RenameParams parameters); + + /// + /// Delete file from Cloudinary asynchronously. + /// + /// Parameters for deletion of resource from Cloudinary. + /// Results of deletion. + Task DestroyAsync(DeletionParams parameters); + + /// + /// Deletes file from Cloudinary. + /// + /// Parameters for deletion of resource from Cloudinary. + /// Results of deletion. + DeletionResult Destroy(DeletionParams parameters); + + /// + /// Creates and returns an URL that allows downloading the backed-up asset + /// based on the the asset ID and the version ID. + /// + /// ID of the asset. + /// Version ID of the asset. + /// Url for downloading the backed-up asset. + string DownloadBackedUpAsset(string assetId, string versionId); + + /// + /// Manage tag assignments asynchronously. + /// + /// Parameters of tag management. + /// (Optional) Cancellation token. + /// Results of tags management. + Task TagAsync(TagParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Manages tag assignments. + /// + /// Parameters of tag management. + /// Results of tags management. + TagResult Tag(TagParams parameters); + + /// + /// Manages context assignments asynchronously. + /// + /// Parameters of context management. + /// (Optional) Cancellation token. + /// Results of contexts management. + Task ContextAsync(ContextParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Manages context assignments. + /// + /// Parameters of context management. + /// Results of contexts management. + ContextResult Context(ContextParams parameters); + + /// + /// This method can be used to force refresh facebook and twitter profile pictures. The response of this method + /// includes the image's version. Use this version to bypass previously cached CDN copies. Also it can be used + /// to generate transformed versions of an uploaded image. This is useful when Strict Transformations are + /// allowed for your account and you wish to create custom derived images for already uploaded images asynchronously. + /// + /// The parameters for explicit method. + /// (Optional) Cancellation token. + /// Parsed response after a call of Explicit method. + Task ExplicitAsync(ExplicitParams parameters, CancellationToken? cancellationToken = null); + + /// + /// This method can be used to force refresh facebook and twitter profile pictures. The response of this method + /// includes the image's version. Use this version to bypass previously cached CDN copies. Also it can be used + /// to generate transformed versions of an uploaded image. This is useful when Strict Transformations are + /// allowed for your account and you wish to create custom derived images for already uploaded images. + /// + /// The parameters for explicit method. + /// Parsed response after a call of Explicit method. + ExplicitResult Explicit(ExplicitParams parameters); + + /// + /// Explodes multipage document to single pages asynchronously. + /// + /// Parameters of explosion operation. + /// (Optional) Cancellation token. + /// Parsed response after a call of Explode method. + Task ExplodeAsync(ExplodeParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Explodes multipage document to single pages. + /// + /// Parameters of explosion operation. + /// Parsed response after a call of Explode method. + ExplodeResult Explode(ExplodeParams parameters); + + /// + /// Creates a zip archive and stores it as a raw resource in your Cloudinary account asynchronously. + /// + /// Parameters of the new generated zip archive. + /// (Optional) Cancellation token. + /// Parsed result of creating the archive. + Task CreateZipAsync(ArchiveParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Creates a zip archive and stores it as a raw resource in your Cloudinary account. + /// + /// Parameters of the new generated zip archive. + /// Parsed result of creating the archive. + ArchiveResult CreateZip(ArchiveParams parameters); + + /// + /// Creates archive and stores it as a raw resource in your Cloudinary account asynchronously. + /// + /// Parameters of new generated archive. + /// (Optional) Cancellation token. + /// Parsed result of creating the archive. + Task CreateArchiveAsync(ArchiveParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Creates archive and stores it as a raw resource in your Cloudinary account. + /// + /// Parameters of new generated archive. + /// Parsed result of creating the archive. + ArchiveResult CreateArchive(ArchiveParams parameters); + + /// + /// Returns URL on archive file. + /// + /// Parameters of generated archive. + /// URL on archive file. + string DownloadArchiveUrl(ArchiveParams parameters); + + /// + /// Creates and returns an URL that when invoked creates an archive of a folder. + /// + /// Full path from the root. + /// Optional parameters of generated archive. + /// Url for downloading an archive of a folder. + string DownloadFolder(string folderPath, ArchiveParams parameters = null); + + /// + /// Gets URL to download tag cloud as ZIP package. + /// + /// The tag. + /// The transformation. + /// Download URL. + /// Tag should be specified. + /// Resource type (image, video or raw) of files to include in the archive (optional). + string DownloadZip(string tag, Transformation transform, string resourceType = CloudinaryUpload.RESOURCE_TYPE_IMAGE); + + /// + /// Gets URL to download private image. + /// + /// The image public ID. + /// Whether to download image as attachment (optional). + /// Format to download (optional). + /// The type (optional). + /// The date (UNIX time in seconds) for the URL expiration. (optional). + /// Resource type (image, video or raw) of files to include in the archive (optional). + /// Download URL. + /// publicId can't be null. + string DownloadPrivate( + string publicId, + bool? attachment = null, + string format = "", + string type = "", + long? expiresAt = null, + string resourceType = CloudinaryUpload.RESOURCE_TYPE_IMAGE); + + /// + /// Eagerly generate sprites asynchronously. + /// + /// Parameters for sprite generation. + /// (Optional) Cancellation token. + /// Parsed response with detailed information about the created sprite. + Task MakeSpriteAsync(SpriteParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Eagerly generates sprites. + /// + /// Parameters for sprite generation. + /// Parsed response with detailed information about the created sprite. + SpriteResult MakeSprite(SpriteParams parameters); + + /// + /// Gets a signed URL to download generated sprite. + /// + /// Parameters of Sprite operation. + /// Download URL. + string DownloadSprite(SpriteParams parameters); + + /// + /// Creates a single animated GIF file from a group of images asynchronously. + /// + /// Parameters of Multi operation. + /// (Optional) Cancellation token. + /// Parsed response with detailed information about the created animated GIF. + Task MultiAsync(MultiParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Creates a single animated GIF file from a group of images. + /// + /// Parameters of Multi operation. + /// Parsed response with detailed information about the created animated GIF. + MultiResult Multi(MultiParams parameters); + + /// + /// Gets a signed URL to download animated GIF file generated through multi request. + /// + /// Parameters of Multi operation. + /// Download URL. + string DownloadMulti(MultiParams parameters); + + /// + /// Generate an image of a given textual string asynchronously. + /// + /// Text to draw. + /// (Optional) Cancellation token. + /// Results of generating an image of a given textual string. + Task TextAsync(string text, CancellationToken? cancellationToken = null); + + /// + /// Generates an image of a given textual string asynchronously. + /// + /// Parameters of generating an image of a given textual string. + /// (Optional) Cancellation token. + /// Results of generating an image of a given textual string. + Task TextAsync(TextParams parameters, CancellationToken? cancellationToken = null); + + /// + /// Generates an image of a given textual string. + /// + /// Text to draw. + /// Results of generating an image of a given textual string. + TextResult Text(string text); + + /// + /// Generates an image of a given textual string. + /// + /// Parameters of generating an image of a given textual string. + /// Results of generating an image of a given textual string. + TextResult Text(TextParams parameters); + + /// + /// Creates auto-generated video slideshow. + /// + /// Parameters for generating the slideshow. + /// The public id of the generated slideshow. + CreateSlideshowResult CreateSlideshow(CreateSlideshowParams parameters); + + /// + /// Creates auto-generated video slideshow asynchronously. + /// + /// Parameters for generating the slideshow. + /// (Optional) Cancellation token. + /// The public id of the generated slideshow. + Task CreateSlideshowAsync( + CreateSlideshowParams parameters, + CancellationToken? cancellationToken = null); + + /// + /// Gets java script that configures Cloudinary JS. + /// + /// Whether to reference additional scripts that are necessary for uploading files directly from browser. + /// Override location of js files (default: ~/Scripts). + /// HTML script tag with Cloudinary JS configuration. + string GetCloudinaryJsConfig(bool directUpload = false, string dir = ""); + } +} diff --git a/CloudinaryDotNet/Cloudinary.AdminApi.MetadataFields.cs b/CloudinaryDotNet/Cloudinary.AdminApi.MetadataFields.cs index 835046d4..61fe65c1 100644 --- a/CloudinaryDotNet/Cloudinary.AdminApi.MetadataFields.cs +++ b/CloudinaryDotNet/Cloudinary.AdminApi.MetadataFields.cs @@ -9,172 +9,58 @@ /// public partial class Cloudinary { - /// - /// Create a new metadata field definition. - /// - /// Parameters of the metadata field. - /// Parsed result of the metadata field creating. - /// Type of the metadata field. + /// public MetadataFieldResult AddMetadataField(MetadataFieldCreateParams parameters) { - var url = m_api.ApiUrlMetadataFieldV.BuildUrl(); - var result = CallAdminApiAsync(HttpMethod.POST, url, parameters, null, PrepareHeaders()).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.AddMetadataField(parameters); } - /// - /// Retrieve a list of all metadata field definitions as an array of JSON objects. - /// - /// Parsed list of metadata field definitions. + /// public MetadataFieldListResult ListMetadataFields() { - var result = CallAdminApiAsync( - HttpMethod.GET, m_api.ApiUrlMetadataFieldV.BuildUrl(), null, null).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.ListMetadataFields(); } - /// - /// Retrieve a single metadata field definition. - /// - /// The ID of the metadata field. - /// Parsed information about metadata field. + /// public MetadataFieldResult GetMetadataField(string fieldExternalId) { - var url = m_api.ApiUrlMetadataFieldV.Add(fieldExternalId).BuildUrl(); - var result = CallAdminApiAsync(HttpMethod.GET, url, null, null).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.GetMetadataField(fieldExternalId); } - /// - /// Update a metadata field by its external ID. - /// There is no need to pass the entire object, only properties to be updated. - /// - /// The ID of the metadata field. - /// Parameters of the metadata field to be updated. - /// Parsed result of the operation. - /// Type of the metadata field. + /// public MetadataFieldResult UpdateMetadataField(string fieldExternalId, MetadataFieldUpdateParams parameters) { - if (string.IsNullOrEmpty(fieldExternalId)) - { - throw new ArgumentNullException(nameof(fieldExternalId)); - } - - var url = m_api.ApiUrlMetadataFieldV.Add(fieldExternalId).BuildUrl(); - var result = CallAdminApiAsync(HttpMethod.PUT, url, parameters, null, PrepareHeaders()).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.UpdateMetadataField(fieldExternalId, parameters); } - /// - /// Update the datasource of a supported field type (currently only enum and set). - /// The update is partial: datasource entries with an existing external_id will be updated. - /// Entries with new external_id’s (or without external_id’s) will be appended. - /// - /// The ID of the metadata field. - /// Parameters of the datasource to be updated. - /// Parsed result of the operation. + /// public MetadataDataSourceResult UpdateMetadataDataSourceEntries(string fieldExternalId, MetadataDataSourceParams parameters) { - if (string.IsNullOrEmpty(fieldExternalId)) - { - throw new ArgumentNullException(nameof(fieldExternalId)); - } - - var url = m_api.ApiUrlMetadataFieldV.Add(fieldExternalId).Add(Constants.DATASOURCE_MANAGMENT).BuildUrl(); - var result = CallAdminApiAsync(HttpMethod.PUT, url, parameters, null, PrepareHeaders()).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.UpdateMetadataDataSourceEntries(fieldExternalId, parameters); } - /// - /// Delete a metadata field definition. - /// The field should no longer be considered a valid candidate for all other endpoints. - /// - /// The ID of the metadata field. - /// Parsed result of the operation. + /// public DelMetadataFieldResult DeleteMetadataField(string fieldExternalId) { - if (string.IsNullOrEmpty(fieldExternalId)) - { - throw new ArgumentNullException(nameof(fieldExternalId)); - } - - var url = m_api.ApiUrlMetadataFieldV.Add(fieldExternalId).BuildUrl(); - var result = CallAdminApiAsync(HttpMethod.DELETE, url, null, null).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.DeleteMetadataField(fieldExternalId); } - /// - /// Delete datasource entries for a specified metadata field definition. - /// This operation sets the state of the entries to inactive. - /// - /// The ID of the metadata field. - /// An array of IDs of datasource entries to delete. - /// Parsed result of the operation. + /// public MetadataDataSourceResult DeleteMetadataDataSourceEntries(string fieldExternalId, List entriesExternalIds) { - var url = PrepareUrlForDatasourceOperation(fieldExternalId, entriesExternalIds, Constants.DATASOURCE_MANAGMENT); - var result = CallAdminApiAsync(HttpMethod.DELETE, url, null, null).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.DeleteMetadataDataSourceEntries(fieldExternalId, entriesExternalIds); } - /// - /// Restore (unblock) any previously deleted datasource entries for a specified metadata field definition - /// and set the state of the entries to active. - /// - /// The ID of the metadata field. - /// An array of IDs of datasource entries to restore. - /// Parsed result of the operation. + /// public MetadataDataSourceResult RestoreMetadataDataSourceEntries(string fieldExternalId, List entriesExternalIds) { - var url = PrepareUrlForDatasourceOperation(fieldExternalId, entriesExternalIds, $"{Constants.DATASOURCE_MANAGMENT}_restore"); - var result = CallAdminApiAsync(HttpMethod.POST, url, null, null).GetAwaiter().GetResult(); - return result; + return cloudinaryAdmin.RestoreMetadataDataSourceEntries(fieldExternalId, entriesExternalIds); } - /// - /// Populate metadata fields with the given values. Existing values will be overwritten. - /// - /// Any metadata-value pairs given are merged with any existing metadata-value pairs - /// (an empty value for an existing metadata field clears the value). - /// - /// Values to be applied to metadata fields of uploaded assets. - /// Parsed result of the operation. + /// public MetadataUpdateResult UpdateMetadata(MetadataUpdateParams parameters) { - var url = GetApiUrlV(). - Add(Api.GetCloudinaryParam(parameters.ResourceType)). - Add(Constants.METADATA). - BuildUrl(); - var result = CallAdminApiAsync(HttpMethod.POST, url, parameters, null).GetAwaiter().GetResult(); - return result; - } - - private static Dictionary PrepareHeaders() - { - var extraHeaders = new Dictionary - { - { - Constants.HEADER_CONTENT_TYPE, - Constants.CONTENT_TYPE_APPLICATION_JSON - }, - }; - - return extraHeaders; - } - - private string PrepareUrlForDatasourceOperation(string fieldExternalId, List entriesExternalIds, string actionName) - { - if (string.IsNullOrEmpty(fieldExternalId)) - { - throw new ArgumentNullException(nameof(fieldExternalId)); - } - - var parameters = new DataSourceEntriesParams(entriesExternalIds); - var urlBuilder = new UrlBuilder( - m_api.ApiUrlMetadataFieldV.Add(fieldExternalId).Add(actionName).BuildUrl(), - parameters.ToParamsDictionary()); - var url = urlBuilder.ToString(); - return url; + return cloudinaryAdmin.UpdateMetadata(parameters); } } } diff --git a/CloudinaryDotNet/Cloudinary.AdminApi.StreamingProfiles.cs b/CloudinaryDotNet/Cloudinary.AdminApi.StreamingProfiles.cs index 5d06fb90..bd0b5a55 100644 --- a/CloudinaryDotNet/Cloudinary.AdminApi.StreamingProfiles.cs +++ b/CloudinaryDotNet/Cloudinary.AdminApi.StreamingProfiles.cs @@ -10,169 +10,47 @@ /// public partial class Cloudinary { - /// - /// Create a new streaming profile asynchronously. - /// - /// Parameters of streaming profile creating. - /// (Optional) Cancellation token. - /// Detailed information about created streaming profile. + /// public Task CreateStreamingProfileAsync(StreamingProfileCreateParams parameters, CancellationToken? cancellationToken = null) => - CallStreamingProfileApiAsync(HttpMethod.POST, parameters, cancellationToken); + cloudinaryAdmin.CreateStreamingProfileAsync(parameters, cancellationToken); - /// - /// Create a new streaming profile. - /// - /// Parameters of streaming profile creating. - /// Detailed information about created streaming profile. + /// public StreamingProfileResult CreateStreamingProfile(StreamingProfileCreateParams parameters) => - CallStreamingProfileApi(HttpMethod.POST, parameters); + cloudinaryAdmin.CreateStreamingProfile(parameters); - /// - /// Update streaming profile asynchronously. - /// - /// Name to be assigned to a streaming profile. - /// Parameters of streaming profile updating. - /// (Optional) Cancellation token. - /// parameters can't be null. - /// name can't be null or empty. - /// Result of updating the streaming profile. + /// public Task UpdateStreamingProfileAsync( string name, StreamingProfileUpdateParams parameters, - CancellationToken? cancellationToken = null) - { - ValidateCallStreamingProfileApiParameters(name, parameters); - return CallStreamingProfileApiAsync(HttpMethod.PUT, parameters, cancellationToken); - } + CancellationToken? cancellationToken = null) => + cloudinaryAdmin.UpdateStreamingProfileAsync(name, parameters, cancellationToken); - /// - /// Update streaming profile. - /// - /// Name to be assigned to a streaming profile. - /// Parameters of streaming profile updating. - /// both arguments can't be null. - /// Result of updating the streaming profile. - public StreamingProfileResult UpdateStreamingProfile(string name, StreamingProfileUpdateParams parameters) - { - ValidateCallStreamingProfileApiParameters(name, parameters); - return CallStreamingProfileApi(HttpMethod.PUT, parameters, name); - } + /// + public StreamingProfileResult UpdateStreamingProfile(string name, StreamingProfileUpdateParams parameters) => + cloudinaryAdmin.UpdateStreamingProfile(name, parameters); - /// - /// Delete streaming profile asynchronously. - /// - /// The Name of streaming profile. - /// (Optional) Cancellation token. - /// name can't be null. - /// Result of removing the streaming profile. - public Task DeleteStreamingProfileAsync(string name, CancellationToken? cancellationToken = null) - { - ValidateNameForCallStreamingProfileApiParameters(name); - return CallStreamingProfileApiAsync(HttpMethod.DELETE, null, cancellationToken, name); - } + /// + public Task DeleteStreamingProfileAsync(string name, CancellationToken? cancellationToken = null) => + cloudinaryAdmin.DeleteStreamingProfileAsync(name, cancellationToken); - /// - /// Delete streaming profile. - /// - /// Streaming profile name to delete. - /// name can't be null. - /// Result of removing the streaming profile. - public StreamingProfileResult DeleteStreamingProfile(string name) - { - ValidateNameForCallStreamingProfileApiParameters(name); - return CallStreamingProfileApi(HttpMethod.DELETE, null, name); - } + /// + public StreamingProfileResult DeleteStreamingProfile(string name) => + cloudinaryAdmin.DeleteStreamingProfile(name); - /// - /// Retrieve the details of a single streaming profile by name asynchronously. - /// - /// The Name of streaming profile. - /// (Optional) Cancellation token. - /// name can't be null. - /// Detailed information about the streaming profile. - public Task GetStreamingProfileAsync(string name, CancellationToken? cancellationToken = null) - { - ValidateNameForCallStreamingProfileApiParameters(name); - return CallStreamingProfileApiAsync(HttpMethod.GET, null, cancellationToken, name); - } + /// + public Task GetStreamingProfileAsync(string name, CancellationToken? cancellationToken = null) => + cloudinaryAdmin.GetStreamingProfileAsync(name, cancellationToken); - /// - /// Retrieve the details of a single streaming profile by name. - /// - /// Streaming profile name. - /// name can't be null. - /// Detailed information about the streaming profile. - public StreamingProfileResult GetStreamingProfile(string name) - { - ValidateNameForCallStreamingProfileApiParameters(name); - return CallStreamingProfileApi(HttpMethod.GET, null, name); - } + /// + public StreamingProfileResult GetStreamingProfile(string name) => + cloudinaryAdmin.GetStreamingProfile(name); - /// - /// Retrieve the list of streaming profiles, including built-in and custom profiles asynchronously. - /// - /// (Optional) Cancellation token. - /// Detailed information about streaming profiles. - public Task ListStreamingProfilesAsync(CancellationToken? cancellationToken = null) - { - return CallAdminApiAsync( - HttpMethod.GET, - m_api.ApiUrlStreamingProfileV.BuildUrl(), - null, - cancellationToken); - } + /// + public Task ListStreamingProfilesAsync(CancellationToken? cancellationToken = null) => + cloudinaryAdmin.ListStreamingProfilesAsync(cancellationToken); - /// - /// Retrieve the list of streaming profiles, including built-in and custom profiles. - /// - /// Detailed information about streaming profiles. - public StreamingProfileListResult ListStreamingProfiles() - { - return ListStreamingProfilesAsync().GetAwaiter().GetResult(); - } - - private static void ValidateCallStreamingProfileApiParameters(string name, StreamingProfileUpdateParams parameters) - { - ValidateNameForCallStreamingProfileApiParameters(name); - ValidateStreamingProfileUpdateParams(parameters); - } - - private static void ValidateStreamingProfileUpdateParams(StreamingProfileUpdateParams parameters) - { - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } - } - - private static void ValidateNameForCallStreamingProfileApiParameters(string name) - { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException("Name parameter should be defined", nameof(name)); - } - } - - private Task CallStreamingProfileApiAsync( - HttpMethod httpMethod, - BaseParams parameters, - CancellationToken? cancellationToken, - string name = null) - { - return CallAdminApiAsync( - httpMethod, - m_api.ApiUrlStreamingProfileV.Add(name).BuildUrl(), - parameters, - cancellationToken); - } - - private StreamingProfileResult CallStreamingProfileApi(HttpMethod httpMethod, BaseParams parameters, string name = null) - { - return CallStreamingProfileApiAsync( - httpMethod, - parameters, - null, - name).GetAwaiter().GetResult(); - } + /// + public StreamingProfileListResult ListStreamingProfiles() => + cloudinaryAdmin.ListStreamingProfiles(); } } diff --git a/CloudinaryDotNet/Cloudinary.AdminApi.cs b/CloudinaryDotNet/Cloudinary.AdminApi.cs index a1e876a9..16c54ee2 100644 --- a/CloudinaryDotNet/Cloudinary.AdminApi.cs +++ b/CloudinaryDotNet/Cloudinary.AdminApi.cs @@ -12,2111 +12,770 @@ namespace CloudinaryDotNet /// Main class of Cloudinary .NET API. /// [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Reviewed.")] - public partial class Cloudinary + public partial class Cloudinary : ICloudinaryAdmin { - /// - /// Gets the advanced search provider used by the Cloudinary instance. - /// - /// Instance of the class. + private readonly ICloudinaryAdmin cloudinaryAdmin; + + /// public Search Search() { - return new Search(m_api); + return cloudinaryAdmin.Search(); } - /// - /// Lists resource types asynchronously. - /// - /// (Optional) Cancellation token. - /// Parsed list of resource types. + /// public Task ListResourceTypesAsync(CancellationToken? cancellationToken = null) { - return CallAdminApiAsync(HttpMethod.GET, GetResourcesUrl().BuildUrl(), null, cancellationToken); + return cloudinaryAdmin.ListResourceTypesAsync(cancellationToken); } - /// - /// Lists resource types. - /// - /// Parsed list of resource types. + /// public ListResourceTypesResult ListResourceTypes() { - return ListResourceTypesAsync().GetAwaiter().GetResult(); - } - - /// - /// Lists resources asynchronously asynchronously. - /// - /// Starting position. - /// Whether to include tags in result. - /// Whether to include context in result. - /// Whether to include moderation status in result. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesAsync( - string nextCursor = null, - bool tags = true, - bool context = true, - bool moderations = true, - CancellationToken? cancellationToken = null) - { - var listResourcesParams = new ListResourcesParams() - { - NextCursor = nextCursor, - Tags = tags, - Context = context, - Moderations = moderations, - }; - return ListResourcesAsync(listResourcesParams, cancellationToken); - } - - /// - /// Lists resources. - /// - /// Starting position. - /// Whether to include tags in result. - /// Whether to include context in result. - /// Whether to include moderation status in result. - /// Parsed result of the resources listing. - public ListResourcesResult ListResources( - string nextCursor = null, - bool tags = true, - bool context = true, - bool moderations = true) - { - return ListResourcesAsync(nextCursor, tags, context, moderations) - .GetAwaiter().GetResult(); - } - - /// - /// Lists resources of specified type asynchronously. - /// - /// Resource type. - /// Starting position. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesByTypeAsync( - string type, - string nextCursor = null, - CancellationToken? cancellationToken = null) - { - var listResourcesParams = new ListResourcesParams() - { - Type = type, - NextCursor = nextCursor, - }; - - return ListResourcesAsync(listResourcesParams, cancellationToken); - } - - /// - /// Lists resources of specified type. - /// - /// Resource type. - /// Starting position. - /// Parsed result of the resources listing. + return cloudinaryAdmin.ListResourceTypes(); + } + + /// + public Task ListResourcesAsync(string nextCursor = null, bool tags = true, bool context = true, bool moderations = true, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourcesAsync(nextCursor, tags, context, moderations, cancellationToken); + } + + /// + public Task ListResourcesAsync(ListResourcesParams parameters, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourcesAsync(parameters, cancellationToken); + } + + /// + public ListResourcesResult ListResources(string nextCursor = null, bool tags = true, bool context = true, bool moderations = true) + { + return cloudinaryAdmin.ListResources(nextCursor, tags, context, moderations); + } + + /// + public ListResourcesResult ListResources(ListResourcesParams parameters) + { + return cloudinaryAdmin.ListResources(parameters); + } + + /// + public Task ListResourcesByTypeAsync(string type, string nextCursor = null, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourcesByTypeAsync(type, nextCursor, cancellationToken); + } + + /// public ListResourcesResult ListResourcesByType(string type, string nextCursor = null) { - return ListResourcesByTypeAsync(type, nextCursor).GetAwaiter().GetResult(); - } - - /// - /// Lists resources by prefix asynchronously. - /// - /// Public identifier prefix. - /// Resource type. - /// Starting position. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesByPrefixAsync( - string prefix, - string type = "upload", - string nextCursor = null, - CancellationToken? cancellationToken = null) - { - var listResourcesByPrefixParams = new ListResourcesByPrefixParams() - { - Type = type, - Prefix = prefix, - NextCursor = nextCursor, - }; - return ListResourcesAsync(listResourcesByPrefixParams, cancellationToken); - } - - /// - /// Lists resources by prefix. - /// - /// Public identifier prefix. - /// Resource type. - /// Starting position. - /// Parsed result of the resources listing. - public ListResourcesResult ListResourcesByPrefix( - string prefix, - string type = "upload", - string nextCursor = null) - { - return ListResourcesByPrefixAsync(prefix, type, nextCursor) - .GetAwaiter().GetResult(); - } - - /// - /// Lists resources by prefix asynchronously. - /// - /// Public identifier prefix. - /// Whether to include tags in result. - /// Whether to include context in result. - /// If true, include moderation status for each resource. - /// Resource type. - /// Starting position. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesByPrefixAsync( - string prefix, - bool tags, - bool context, - bool moderations, - string type = "upload", - string nextCursor = null, - CancellationToken? cancellationToken = null) - { - var listResourcesByPrefixParams = new ListResourcesByPrefixParams() - { - Tags = tags, - Context = context, - Moderations = moderations, - Type = type, - Prefix = prefix, - NextCursor = nextCursor, - }; - return ListResourcesAsync(listResourcesByPrefixParams, cancellationToken); - } - - /// - /// Lists resources by prefix. - /// - /// Public identifier prefix. - /// Whether to include tags in result. - /// Whether to include context in result. - /// If true, include moderation status for each resource. - /// Resource type. - /// Starting position. - /// Parsed result of the resources listing. + return cloudinaryAdmin.ListResourcesByType(type, nextCursor); + } + + /// + public Task ListResourcesByPrefixAsync(string prefix, string type = "upload", string nextCursor = null, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourcesByPrefixAsync(prefix, type, nextCursor, cancellationToken); + } + + /// + public Task ListResourcesByPrefixAsync(string prefix, bool tags, bool context, bool moderations, string type = "upload", string nextCursor = null, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourcesByPrefixAsync(prefix, tags, context, moderations, type, nextCursor, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByPrefix(string prefix, string type = "upload", string nextCursor = null) + { + return cloudinaryAdmin.ListResourcesByPrefix(prefix, type, nextCursor); + } + + /// public ListResourcesResult ListResourcesByPrefix(string prefix, bool tags, bool context, bool moderations, string type = "upload", string nextCursor = null) { - return ListResourcesByPrefixAsync(prefix, tags, context, moderations, type, nextCursor) - .GetAwaiter().GetResult(); - } - - /// - /// Lists resources by tag asynchronously. - /// - /// The tag. - /// Starting position. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesByTagAsync( - string tag, - string nextCursor = null, - CancellationToken? cancellationToken = null) - { - var listResourcesByTagParams = new ListResourcesByTagParams() - { - Tag = tag, - NextCursor = nextCursor, - }; - return ListResourcesAsync(listResourcesByTagParams, cancellationToken); - } - - /// - /// Lists resources by tag. - /// - /// The tag. - /// Starting position. - /// Parsed result of the resources listing. + return cloudinaryAdmin.ListResourcesByPrefix(prefix, tags, context, moderations, type, nextCursor); + } + + /// + public Task ListResourcesByTagAsync(string tag, string nextCursor = null, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourcesByTagAsync(tag, nextCursor, cancellationToken); + } + + /// public ListResourcesResult ListResourcesByTag(string tag, string nextCursor = null) { - return ListResourcesByTagAsync(tag, nextCursor).GetAwaiter().GetResult(); + return cloudinaryAdmin.ListResourcesByTag(tag, nextCursor); } - /// - /// Returns resources with specified public identifiers asynchronously. - /// - /// Public identifiers. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesByPublicIdsAsync( - IEnumerable publicIds, - CancellationToken? cancellationToken = null) + /// + public Task ListResourcesByPublicIdsAsync(IEnumerable publicIds, CancellationToken? cancellationToken = null) { - var listSpecificResourcesParams = new ListSpecificResourcesParams() - { - PublicIds = new List(publicIds), - }; - return ListResourcesAsync(listSpecificResourcesParams, cancellationToken); + return cloudinaryAdmin.ListResourcesByPublicIdsAsync(publicIds, cancellationToken); } - /// - /// Returns resources with specified public identifiers. - /// - /// Public identifiers. - /// Parsed result of the resources listing. + /// public ListResourcesResult ListResourcesByPublicIds(IEnumerable publicIds) { - return ListResourcesByPublicIdsAsync(publicIds) - .GetAwaiter().GetResult(); - } - - /// - /// Returns resources with specified public identifiers asynchronously. - /// - /// Public identifiers. - /// Whether to include tags in result. - /// Whether to include context in result. - /// Whether to include moderation status in result. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourceByPublicIdsAsync( - IEnumerable publicIds, - bool tags, - bool context, - bool moderations, - CancellationToken? cancellationToken = null) - { - var listSpecificResourcesParams = new ListSpecificResourcesParams() - { - PublicIds = new List(publicIds), - Tags = tags, - Context = context, - Moderations = moderations, - }; - return ListResourcesAsync(listSpecificResourcesParams, cancellationToken); - } - - /// - /// Returns resources with specified public identifiers. - /// - /// Public identifiers. - /// Whether to include tags in result. - /// Whether to include context in result. - /// Whether to include moderation status in result. - /// Parsed result of the resources listing. + return cloudinaryAdmin.ListResourcesByPublicIds(publicIds); + } + + /// + public Task ListResourceByPublicIdsAsync(IEnumerable publicIds, bool tags, bool context, bool moderations, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourceByPublicIdsAsync(publicIds, tags, context, moderations, cancellationToken); + } + + /// public ListResourcesResult ListResourceByPublicIds(IEnumerable publicIds, bool tags, bool context, bool moderations) { - return ListResourceByPublicIdsAsync(publicIds, tags, context, moderations) - .GetAwaiter().GetResult(); - } - - /// - /// Lists resources by moderation status asynchronously. - /// - /// The moderation kind. - /// The moderation status. - /// Whether to include tags in result. - /// Whether to include context in result. - /// Whether to include moderation status in result. - /// The next cursor. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesByModerationStatusAsync( - string kind, - ModerationStatus status, - bool tags = true, - bool context = true, - bool moderations = true, - string nextCursor = null, - CancellationToken? cancellationToken = null) - { - var listResourcesByModerationParams = new ListResourcesByModerationParams() - { - ModerationKind = kind, - ModerationStatus = status, - Tags = tags, - Context = context, - Moderations = moderations, - NextCursor = nextCursor, - }; - return ListResourcesAsync(listResourcesByModerationParams, cancellationToken); - } - - /// - /// Lists resources by moderation status. - /// - /// The moderation kind. - /// The moderation status. - /// Whether to include tags in result. - /// Whether to include context in result. - /// Whether to include moderation status in result. - /// The next cursor. - /// Parsed result of the resources listing. - public ListResourcesResult ListResourcesByModerationStatus( - string kind, - ModerationStatus status, - bool tags = true, - bool context = true, - bool moderations = true, - string nextCursor = null) - { - return ListResourcesByModerationStatusAsync(kind, status, tags, context, moderations, nextCursor) - .GetAwaiter().GetResult(); - } - - /// - /// List resources by context metadata keys and values asynchronously. - /// - /// Only resources with the given key should be returned. - /// When provided should only return resources with this given value for the context key. - /// When not provided, return all resources for which the context key exists. - /// If true, include list of tag names assigned for each resource. - /// If true, include context assigned to each resource. - /// The next cursor. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesByContextAsync( - string key, - string value = "", - bool tags = false, - bool context = false, - string nextCursor = null, - CancellationToken? cancellationToken = null) - { - var listResourcesByContextParams = new ListResourcesByContextParams() - { - Key = key, - Value = value, - Tags = tags, - Context = context, - NextCursor = nextCursor, - }; - return ListResourcesAsync(listResourcesByContextParams, cancellationToken); - } - - /// - /// List resources by context metadata keys and values. - /// - /// Only resources with the given key should be returned. - /// When provided should only return resources with this given value for the context key. - /// When not provided, return all resources for which the context key exists. - /// If true, include list of tag names assigned for each resource. - /// If true, include context assigned to each resource. - /// The next cursor. - /// Parsed result of the resources listing. - public ListResourcesResult ListResourcesByContext( - string key, - string value = "", - bool tags = false, - bool context = false, - string nextCursor = null) - { - return ListResourcesByContextAsync(key, value, tags, context, nextCursor) - .GetAwaiter().GetResult(); - } - - /// - /// Gets a list of resources asynchronously. - /// - /// Parameters to list resources. - /// (Optional) Cancellation token. - /// Parsed result of the resources listing. - public Task ListResourcesAsync(ListResourcesParams parameters, CancellationToken? cancellationToken = null) + return cloudinaryAdmin.ListResourceByPublicIds(publicIds, tags, context, moderations); + } + + /// + public Task ListResourcesByModerationStatusAsync(string kind, ModerationStatus status, bool tags = true, bool context = true, bool moderations = true, string nextCursor = null, CancellationToken? cancellationToken = null) { - var url = GetListResourcesUrl(parameters); - return CallAdminApiAsync(HttpMethod.GET, url, parameters, cancellationToken); + return cloudinaryAdmin.ListResourcesByModerationStatusAsync(kind, status, tags, context, moderations, nextCursor, cancellationToken); } - /// - /// Gets a list of resources. - /// - /// Parameters to list resources. - /// Parsed result of the resources listing. - public ListResourcesResult ListResources(ListResourcesParams parameters) + /// + public ListResourcesResult ListResourcesByModerationStatus(string kind, ModerationStatus status, bool tags = true, bool context = true, bool moderations = true, string nextCursor = null) + { + return cloudinaryAdmin.ListResourcesByModerationStatus(kind, status, tags, context, moderations, nextCursor); + } + + /// + public Task ListResourcesByContextAsync(string key, string value = "", bool tags = false, bool context = false, string nextCursor = null, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.ListResourcesByContextAsync(key, value, tags, context, nextCursor, cancellationToken); + } + + /// + public ListResourcesResult ListResourcesByContext(string key, string value = "", bool tags = false, bool context = false, string nextCursor = null) { - return ListResourcesAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryAdmin.ListResourcesByContext(key, value, tags, context, nextCursor); } - /// - /// Publishes resources by prefix asynchronously. - /// - /// The prefix for publishing resources. - /// Parameters for publishing of resources. - /// Cancellation token. - /// Parsed result of publishing. - public Task PublishResourceByPrefixAsync( - string prefix, - PublishResourceParams parameters, - CancellationToken? cancellationToken) + /// + public Task PublishResourceByPrefixAsync(string prefix, PublishResourceParams parameters, CancellationToken? cancellationToken) { - return PublishResourceAsync("prefix", prefix, parameters, cancellationToken); + return cloudinaryAdmin.PublishResourceByPrefixAsync(prefix, parameters, cancellationToken); } - /// - /// Publishes resources by prefix. - /// - /// The prefix for publishing resources. - /// Parameters for publishing of resources. - /// Parsed result of publishing. + /// public PublishResourceResult PublishResourceByPrefix(string prefix, PublishResourceParams parameters) { - return PublishResource("prefix", prefix, parameters); + return cloudinaryAdmin.PublishResourceByPrefix(prefix, parameters); } - /// - /// Publishes resources by tag asynchronously. - /// - /// All resources with the given tag will be published. - /// Parameters for publishing of resources. - /// (Optional) Cancellation token. - /// Parsed result of publishing. - public Task PublishResourceByTagAsync( - string tag, - PublishResourceParams parameters, - CancellationToken? cancellationToken = null) + /// + public Task PublishResourceByTagAsync(string tag, PublishResourceParams parameters, CancellationToken? cancellationToken = null) { - return PublishResourceAsync("tag", tag, parameters, cancellationToken); + return cloudinaryAdmin.PublishResourceByTagAsync(tag, parameters, cancellationToken); } - /// - /// Publishes resources by tag. - /// - /// All resources with the given tag will be published. - /// Parameters for publishing of resources. - /// Parsed result of publishing. + /// public PublishResourceResult PublishResourceByTag(string tag, PublishResourceParams parameters) { - return PublishResource("tag", tag, parameters); + return cloudinaryAdmin.PublishResourceByTag(tag, parameters); } - /// - /// Publishes resource by Id asynchronously. - /// - /// Not used. - /// Parameters for publishing of resources. - /// Cancellation token. - /// Structure with the results of publishing. - [SuppressMessage("Microsoft.Usage", "CA1801: Review unused parameters", Justification = "Reviewed.")] - public Task PublishResourceByIdsAsync( - string tag, - PublishResourceParams parameters, - CancellationToken? cancellationToken) + /// + public Task PublishResourceByIdsAsync(string tag, PublishResourceParams parameters, CancellationToken? cancellationToken) { - return PublishResourceAsync(string.Empty, string.Empty, parameters, cancellationToken); + return cloudinaryAdmin.PublishResourceByIdsAsync(tag, parameters, cancellationToken); } - /// - /// Publishes resource by Id. - /// - /// Not used. - /// Parameters for publishing of resources. - /// Structure with the results of publishing. - [SuppressMessage("Microsoft.Usage", "CA1801: Review unused parameters", Justification = "Reviewed.")] + /// public PublishResourceResult PublishResourceByIds(string tag, PublishResourceParams parameters) { - return PublishResource(string.Empty, string.Empty, parameters); + return cloudinaryAdmin.PublishResourceByIds(tag, parameters); } - /// - /// Updates access mode for the resources selected by tag asynchronously. - /// - /// Update all resources with the given tag (up to a maximum - /// of 100 matching original resources). - /// Parameters for updating of resources. - /// (Optional) Cancellation token. - /// Structure with the results of update. - public Task UpdateResourceAccessModeByTagAsync( - string tag, - UpdateResourceAccessModeParams parameters, - CancellationToken? cancellationToken = null) + /// + public Task UpdateResourceAccessModeByTagAsync(string tag, UpdateResourceAccessModeParams parameters, CancellationToken? cancellationToken = null) { - return UpdateResourceAccessModeAsync(Constants.TAG_PARAM_NAME, tag, parameters, cancellationToken); + return cloudinaryAdmin.UpdateResourceAccessModeByTagAsync(tag, parameters, cancellationToken); } - /// - /// Updates access mode for the resources selected by tag. - /// - /// Update all resources with the given tag (up to a maximum - /// of 100 matching original resources). - /// Parameters for updating of resources. - /// Structure with the results of update. + /// public UpdateResourceAccessModeResult UpdateResourceAccessModeByTag(string tag, UpdateResourceAccessModeParams parameters) { - return UpdateResourceAccessMode(Constants.TAG_PARAM_NAME, tag, parameters); - } - - /// - /// Updates access mode for the resources selected by prefix asynchronously. - /// - /// Update all resources where the public ID starts with the given prefix (up to a maximum - /// of 100 matching original resources). - /// Parameters for updating of resources. - /// (Optional) Cancellation token. - /// Structure with the results of update. - public Task UpdateResourceAccessModeByPrefixAsync( - string prefix, - UpdateResourceAccessModeParams parameters, - CancellationToken? cancellationToken = null) - { - return UpdateResourceAccessModeAsync(Constants.PREFIX_PARAM_NAME, prefix, parameters, cancellationToken); - } - - /// - /// Updates access mode for the resources selected by prefix. - /// - /// Update all resources where the public ID starts with the given prefix (up to a maximum - /// of 100 matching original resources). - /// Parameters for updating of resources. - /// Structure with the results of update. - public UpdateResourceAccessModeResult UpdateResourceAccessModeByPrefix( - string prefix, - UpdateResourceAccessModeParams parameters) - { - return UpdateResourceAccessMode(Constants.PREFIX_PARAM_NAME, prefix, parameters); - } - - /// - /// Updates access mode for the resources selected by public ids asynchronously. - /// - /// Parameters for updating of resources. Update all resources with the given - /// public IDs (array of up to 100 public_ids). - /// (Optional) Cancellation token. - /// Structure with the results of update. - public Task UpdateResourceAccessModeByIdsAsync( - UpdateResourceAccessModeParams parameters, CancellationToken? cancellationToken = null) - { - return UpdateResourceAccessModeAsync(string.Empty, string.Empty, parameters, cancellationToken); - } - - /// - /// Updates access mode for the resources selected by public ids. - /// - /// Parameters for updating of resources. Update all resources with the given - /// public IDs (array of up to 100 public_ids). - /// Structure with the results of update. + return cloudinaryAdmin.UpdateResourceAccessModeByTag(tag, parameters); + } + + /// + public Task UpdateResourceAccessModeByPrefixAsync(string prefix, UpdateResourceAccessModeParams parameters, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.UpdateResourceAccessModeByPrefixAsync(prefix, parameters, cancellationToken); + } + + /// + public UpdateResourceAccessModeResult UpdateResourceAccessModeByPrefix(string prefix, UpdateResourceAccessModeParams parameters) + { + return cloudinaryAdmin.UpdateResourceAccessModeByPrefix(prefix, parameters); + } + + /// + public Task UpdateResourceAccessModeByIdsAsync(UpdateResourceAccessModeParams parameters, CancellationToken? cancellationToken = null) + { + return cloudinaryAdmin.UpdateResourceAccessModeByIdsAsync(parameters, cancellationToken); + } + + /// public UpdateResourceAccessModeResult UpdateResourceAccessModeByIds(UpdateResourceAccessModeParams parameters) { - return UpdateResourceAccessMode(string.Empty, string.Empty, parameters); + return cloudinaryAdmin.UpdateResourceAccessModeByIds(parameters); } - /// - /// Deletes derived resources by the given transformation (should be specified in parameters) asynchronously. - /// - /// Parameters to delete derived resources. - /// (Optional) Cancellation token. - /// Parsed result of deletion derived resources. + /// public Task DeleteDerivedResourcesByTransformAsync(DelDerivedResParams parameters, CancellationToken? cancellationToken = null) { - UrlBuilder urlBuilder = new UrlBuilder( - GetApiUrlV(). - Add("derived_resources"). - BuildUrl(), - parameters.ToParamsDictionary()); - - return CallAdminApiAsync( - HttpMethod.DELETE, - urlBuilder.ToString(), - parameters, - cancellationToken); + return cloudinaryAdmin.DeleteDerivedResourcesByTransformAsync(parameters, cancellationToken); } - /// - /// Deletes derived resources by the given transformation (should be specified in parameters). - /// - /// Parameters to delete derived resources. - /// Parsed result of deletion derived resources. + /// public DelDerivedResResult DeleteDerivedResourcesByTransform(DelDerivedResParams parameters) { - return DeleteDerivedResourcesByTransformAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryAdmin.DeleteDerivedResourcesByTransform(parameters); } - /// - /// Async call to get a list of folders in the root asynchronously. - /// - /// (optional) Parameters for managing folders list. - /// (Optional) Cancellation token. - /// Parsed result of folders listing. + /// public Task RootFoldersAsync(GetFoldersParams parameters = null, CancellationToken? cancellationToken = null) { - return CallAdminApiAsync(HttpMethod.GET, GetFolderUrl(parameters: parameters), parameters, cancellationToken); + return cloudinaryAdmin.RootFoldersAsync(parameters, cancellationToken); } - /// - /// Gets a list of folders in the root. - /// - /// (optional) Parameters for managing folders list. - /// Parsed result of folders listing. + /// public GetFoldersResult RootFolders(GetFoldersParams parameters = null) { - return RootFoldersAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.RootFolders(parameters); } - /// - /// Gets a list of subfolders in a specified folder asynchronously. - /// - /// The folder name. - /// (Optional) Cancellation token. - /// Parsed result of folders listing. + /// public Task SubFoldersAsync(string folder, CancellationToken? cancellationToken = null) { - return SubFoldersAsync(folder, null, cancellationToken); + return cloudinaryAdmin.SubFoldersAsync(folder, cancellationToken); } - /// - /// Gets a list of subfolders in a specified folder asynchronously. - /// - /// The folder name. - /// (Optional) Parameters for managing folders list. - /// (Optional) Cancellation token. - /// Parsed result of folders listing. + /// public Task SubFoldersAsync(string folder, GetFoldersParams parameters, CancellationToken? cancellationToken = null) { - CheckFolderParameter(folder); - - return CallAdminApiAsync( - HttpMethod.GET, - GetFolderUrl(folder, parameters), - null, - cancellationToken); + return cloudinaryAdmin.SubFoldersAsync(folder, parameters, cancellationToken); } - /// - /// Gets a list of subfolders in a specified folder. - /// - /// The folder name. - /// (Optional) Parameters for managing folders list. - /// Parsed result of folders listing. + /// public GetFoldersResult SubFolders(string folder, GetFoldersParams parameters = null) { - return SubFoldersAsync( - folder, - parameters, - null).GetAwaiter().GetResult(); + return cloudinaryAdmin.SubFolders(folder, parameters); } - /// - /// Deletes folder asynchronously. - /// - /// Folder name. - /// (Optional) Cancellation token. - /// Parsed result of folder deletion. + /// public Task DeleteFolderAsync(string folder, CancellationToken? cancellationToken = null) { - var uri = GetFolderUrl(folder); - return CallAdminApiAsync( - HttpMethod.DELETE, - uri, - null, - cancellationToken); + return cloudinaryAdmin.DeleteFolderAsync(folder, cancellationToken); } - /// - /// Deletes folder. - /// - /// Folder name. - /// Parsed result of folder deletion. + /// public DeleteFolderResult DeleteFolder(string folder) { - return DeleteFolderAsync(folder, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.DeleteFolder(folder); } - /// - /// Create a new empty folder. - /// - /// The full path of the new folder to create. - /// Parsed result of folder creation. + /// public CreateFolderResult CreateFolder(string folder) { - return CreateFolderAsync( - folder, - null).GetAwaiter().GetResult(); + return cloudinaryAdmin.CreateFolder(folder); } - /// - /// Create a new empty folder. - /// - /// The full path of the new folder to create. - /// (Optional) Cancellation token. - /// Parsed result of folder creation. + /// public Task CreateFolderAsync(string folder, CancellationToken? cancellationToken = null) { - CheckIfNotEmpty(folder); - - return CallAdminApiAsync( - HttpMethod.POST, - GetFolderUrl(folder), - null, - cancellationToken); + return cloudinaryAdmin.CreateFolderAsync(folder, cancellationToken); } - /// - /// Creates the upload preset. - /// Upload presets allow you to define the default behavior for your uploads, instead of - /// receiving these as parameters during the upload request itself. Upload presets have - /// precedence over client-side upload parameters asynchronously. - /// - /// Parameters of the upload preset. - /// (Optional) Cancellation token. - /// Parsed response after manipulation of upload presets. + /// public Task CreateUploadPresetAsync(UploadPresetParams parameters, CancellationToken? cancellationToken = null) { - string url = GetApiUrlV(). - Add("upload_presets"). - BuildUrl(); - - return CallAdminApiAsync( - HttpMethod.POST, - url, - parameters, - cancellationToken); + return cloudinaryAdmin.CreateUploadPresetAsync(parameters, cancellationToken); } - /// - /// Creates the upload preset. - /// Upload presets allow you to define the default behavior for your uploads, instead of receiving these as parameters during the upload request itself. Upload presets have precedence over client-side upload parameters. - /// - /// Parameters of the upload preset. - /// Parsed response after manipulation of upload presets. + /// public UploadPresetResult CreateUploadPreset(UploadPresetParams parameters) { - return CreateUploadPresetAsync(parameters, null).GetAwaiter().GetResult(); - } - - /// - /// Updates the upload preset. - /// Every update overwrites all the preset settings asynchronously. - /// File specified as null because it's non-uploading action. - /// - /// New parameters for upload preset. - /// (Optional) Cancellation token. - /// Parsed response after manipulation of upload presets. - public Task UpdateUploadPresetAsync(UploadPresetParams parameters, CancellationToken? cancellationToken = null) => - CallApiAsync(PrepareUploadPresetApiParams(parameters), cancellationToken); - - /// - /// Updates the upload preset. - /// Every update overwrites all the preset settings. - /// File specified as null because it's non-uploading action. - /// - /// New parameters for upload preset. - /// Parsed response after manipulation of upload presets. - public UploadPresetResult UpdateUploadPreset(UploadPresetParams parameters) => - CallApi(PrepareUploadPresetApiParams(parameters)); - - /// - /// Gets the upload preset asynchronously. - /// - /// Name of the upload preset. - /// (Optional) Cancellation token. - /// Upload preset details. - public Task GetUploadPresetAsync(string name, CancellationToken? cancellationToken = null) + return cloudinaryAdmin.CreateUploadPreset(parameters); + } + + /// + public Task UpdateUploadPresetAsync(UploadPresetParams parameters, CancellationToken? cancellationToken = null) { - var url = GetApiUrlV() - .Add("upload_presets") - .Add(name) - .BuildUrl(); + return cloudinaryAdmin.UpdateUploadPresetAsync(parameters, cancellationToken); + } - return CallAdminApiAsync( - HttpMethod.GET, - url, - null, - cancellationToken); + /// + public UploadPresetResult UpdateUploadPreset(UploadPresetParams parameters) + { + return cloudinaryAdmin.UpdateUploadPreset(parameters); } - /// - /// Gets the upload preset. - /// - /// Name of the upload preset. - /// Upload preset details. - public GetUploadPresetResult GetUploadPreset(string name) + /// + public Task GetUploadPresetAsync(string name, CancellationToken? cancellationToken = null) { - return GetUploadPresetAsync(name, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.GetUploadPresetAsync(name, cancellationToken); } - /// - /// Lists upload presets asynchronously. - /// - /// Next cursor. - /// (Optional) Cancellation token. - /// Parsed result of upload presets listing. - public Task ListUploadPresetsAsync(string nextCursor = null, CancellationToken? cancellationToken = null) + /// + public GetUploadPresetResult GetUploadPreset(string name) { - return ListUploadPresetsAsync(new ListUploadPresetsParams() { NextCursor = nextCursor }, cancellationToken); + return cloudinaryAdmin.GetUploadPreset(name); } - /// - /// Lists upload presets. - /// - /// (Optional) Starting position. - /// Parsed result of upload presets listing. - public ListUploadPresetsResult ListUploadPresets(string nextCursor = null) + /// + public Task ListUploadPresetsAsync(string nextCursor = null, CancellationToken? cancellationToken = null) { - return ListUploadPresets(new ListUploadPresetsParams() { NextCursor = nextCursor }); + return cloudinaryAdmin.ListUploadPresetsAsync(nextCursor, cancellationToken); } - /// - /// Lists upload presets asynchronously. - /// - /// Parameters to list upload presets. - /// (Optional) Cancellation token. - /// Parsed result of upload presets listing. + /// public Task ListUploadPresetsAsync(ListUploadPresetsParams parameters, CancellationToken? cancellationToken = null) { - var urlBuilder = new UrlBuilder( - GetApiUrlV() - .Add("upload_presets") - .BuildUrl(), - parameters.ToParamsDictionary()); + return cloudinaryAdmin.ListUploadPresetsAsync(parameters, cancellationToken); + } - return CallAdminApiAsync( - HttpMethod.GET, - urlBuilder.ToString(), - parameters, - cancellationToken); + /// + public ListUploadPresetsResult ListUploadPresets(string nextCursor = null) + { + return cloudinaryAdmin.ListUploadPresets(nextCursor); } - /// - /// Lists upload presets. - /// - /// Parameters to list upload presets. - /// Parsed result of upload presets listing. + /// public ListUploadPresetsResult ListUploadPresets(ListUploadPresetsParams parameters) { - return ListUploadPresetsAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.ListUploadPresets(parameters); } - /// - /// Deletes the upload preset asynchronously. - /// - /// Name of the upload preset. - /// (Optional) Cancellation token. - /// Result of upload preset deletion. + /// public Task DeleteUploadPresetAsync(string name, CancellationToken? cancellationToken = null) { - var url = GetApiUrlV() - .Add("upload_presets") - .Add(name) - .BuildUrl(); - - return CallAdminApiAsync( - HttpMethod.DELETE, - url, - null, - cancellationToken); + return cloudinaryAdmin.DeleteUploadPresetAsync(name, cancellationToken); } - /// - /// Deletes the upload preset. - /// - /// Name of the upload preset. - /// Result of upload preset deletion. + /// public DeleteUploadPresetResult DeleteUploadPreset(string name) { - return DeleteUploadPresetAsync(name, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.DeleteUploadPreset(name); } - /// - /// Gets the Cloudinary account usage details asynchronously. - /// - /// (Optional) The date for the usage report. Must be within the last 3 months. - /// (Optional) Cancellation token. - /// The report on the status of your Cloudinary account usage details. + /// public Task GetUsageAsync(DateTime? date, CancellationToken? cancellationToken = null) { - string uri = GetUsageUrl(date); - - return CallAdminApiAsync( - HttpMethod.GET, - uri, - null, - cancellationToken); + return cloudinaryAdmin.GetUsageAsync(date, cancellationToken); } - /// - /// Gets the Cloudinary account usage details. - /// - /// (Optional) The date for the usage report. Must be within the last 3 months. - /// The report on the status of your Cloudinary account usage details. - public UsageResult GetUsage(DateTime? date = null) + /// + public Task GetUsageAsync(CancellationToken? cancellationToken = null) { - return GetUsageAsync(date, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.GetUsageAsync(cancellationToken); } - /// - /// Gets the Cloudinary account usage details asynchronously. - /// - /// (Optional) Cancellation token. - /// The report on the status of your Cloudinary account usage details. - public Task GetUsageAsync(CancellationToken? cancellationToken = null) + /// + public UsageResult GetUsage(DateTime? date = null) { - string uri = GetUsageUrl(null); - - return CallAdminApiAsync( - HttpMethod.GET, - uri, - null, - cancellationToken); + return cloudinaryAdmin.GetUsage(date); } - /// - /// Gets a list of tags asynchronously. - /// - /// (Optional) Cancellation token. - /// Parsed list of tags. + /// public Task ListTagsAsync(CancellationToken? cancellationToken = null) { - return ListTagsAsync(new ListTagsParams(), cancellationToken); + return cloudinaryAdmin.ListTagsAsync(cancellationToken); } - /// - /// Gets a list of all tags. - /// - /// Parsed list of tags. - public ListTagsResult ListTags() + /// + public Task ListTagsAsync(ListTagsParams parameters, CancellationToken? cancellationToken = null) { - return ListTags(new ListTagsParams()); + return cloudinaryAdmin.ListTagsAsync(parameters, cancellationToken); } - /// - /// Finds all tags that start with the given prefix asynchronously. - /// - /// The tag prefix. - /// (Optional) Cancellation token. - /// Parsed list of tags. - public Task ListTagsByPrefixAsync(string prefix, CancellationToken? cancellationToken = null) + /// + public ListTagsResult ListTags() { - return ListTagsAsync(new ListTagsParams() { Prefix = prefix }, cancellationToken); + return cloudinaryAdmin.ListTags(); } - /// - /// Finds all tags that start with the given prefix. - /// - /// The tag prefix. - /// Parsed list of tags. - public ListTagsResult ListTagsByPrefix(string prefix) + /// + public ListTagsResult ListTags(ListTagsParams parameters) { - return ListTags(new ListTagsParams() { Prefix = prefix }); + return cloudinaryAdmin.ListTags(parameters); } - /// - /// Gets a list of tags asynchronously. - /// - /// Parameters of the request. - /// (Optional) Cancellation token. - /// Parsed list of tags. - public Task ListTagsAsync(ListTagsParams parameters, CancellationToken? cancellationToken = null) + /// + public Task ListTagsByPrefixAsync(string prefix, CancellationToken? cancellationToken = null) { - var urlBuilder = new UrlBuilder( - GetApiUrlV(). - ResourceType("tags"). - Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). - BuildUrl(), - parameters.ToParamsDictionary()); - - return CallAdminApiAsync(HttpMethod.GET, urlBuilder.ToString(), parameters, cancellationToken); + return cloudinaryAdmin.ListTagsByPrefixAsync(prefix, cancellationToken); } - /// - /// Gets a list of tags. - /// - /// Parameters of the request. - /// Parsed list of tags. - public ListTagsResult ListTags(ListTagsParams parameters) + /// + public ListTagsResult ListTagsByPrefix(string prefix) { - return ListTagsAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryAdmin.ListTagsByPrefix(prefix); } - /// - /// Gets a list of transformations asynchronously. - /// - /// (Optional) Cancellation token. - /// Parsed list of transformations details. + /// public Task ListTransformationsAsync(CancellationToken? cancellationToken = null) { - return ListTransformationsAsync(new ListTransformsParams(), cancellationToken); + return cloudinaryAdmin.ListTransformationsAsync(cancellationToken); } - /// - /// Gets a list of transformations. - /// - /// Parsed list of transformations details. - public ListTransformsResult ListTransformations() + /// + public Task ListTransformationsAsync(ListTransformsParams parameters, CancellationToken? cancellationToken = null) { - return ListTransformations(new ListTransformsParams()); + return cloudinaryAdmin.ListTransformationsAsync(parameters, cancellationToken); } - /// - /// Gets a list of transformations asynchronously. - /// - /// Parameters of the request for a list of transformation. - /// (Optional) Cancellation token. - /// Parsed list of transformations details. - public Task ListTransformationsAsync(ListTransformsParams parameters, CancellationToken? cancellationToken = null) + /// + public ListTransformsResult ListTransformations() { - var urlBuilder = new UrlBuilder( - GetApiUrlV(). - ResourceType("transformations"). - BuildUrl(), - parameters.ToParamsDictionary()); - - return CallAdminApiAsync( - HttpMethod.GET, - urlBuilder.ToString(), - parameters, - cancellationToken); + return cloudinaryAdmin.ListTransformations(); } - /// - /// Gets a list of transformations. - /// - /// Parameters of the request for a list of transformation. - /// Parsed list of transformations details. + /// public ListTransformsResult ListTransformations(ListTransformsParams parameters) { - return ListTransformationsAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.ListTransformations(parameters); } - /// - /// Gets details of a single transformation asynchronously. - /// - /// Name of the transformation. - /// (Optional) Cancellation token. - /// Parsed details of a single transformation. + /// public Task GetTransformAsync(string transform, CancellationToken? cancellationToken = null) { - return GetTransformAsync(new GetTransformParams() { Transformation = transform }, cancellationToken); + return cloudinaryAdmin.GetTransformAsync(transform, cancellationToken); } - /// - /// Gets details of a single transformation by name. - /// - /// Name of the transformation. - /// Parsed details of a single transformation. - public GetTransformResult GetTransform(string transform) + /// + public Task GetTransformAsync(GetTransformParams parameters, CancellationToken? cancellationToken = null) { - return GetTransform(new GetTransformParams() { Transformation = transform }); + return cloudinaryAdmin.GetTransformAsync(parameters, cancellationToken); } - /// - /// Gets details of a single transformation asynchronously. - /// - /// Parameters of the request of transformation details. - /// (Optional) Cancellation token. - /// Parsed details of a single transformation. - public Task GetTransformAsync(GetTransformParams parameters, CancellationToken? cancellationToken = null) + /// + public GetTransformResult GetTransform(string transform) { - var urlBuilder = new UrlBuilder( - GetApiUrlV(). - ResourceType("transformations"). - BuildUrl(), - parameters.ToParamsDictionary()); - - return CallAdminApiAsync( - HttpMethod.GET, - urlBuilder.ToString(), - parameters, - cancellationToken); + return cloudinaryAdmin.GetTransform(transform); } - /// - /// Gets details of a single transformation. - /// - /// Parameters of the request of transformation details. - /// Parsed details of a single transformation. + /// public GetTransformResult GetTransform(GetTransformParams parameters) { - return GetTransformAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.GetTransform(parameters); } - /// - /// Updates details of an existing resource asynchronously. - /// - /// The public ID of the resource to update. - /// The image moderation status. - /// (Optional) Cancellation token. - /// Parsed response of the detailed resource information. + /// public Task UpdateResourceAsync(string publicId, ModerationStatus moderationStatus, CancellationToken? cancellationToken = null) { - return UpdateResourceAsync(new UpdateParams(publicId) { ModerationStatus = moderationStatus }, cancellationToken); + return cloudinaryAdmin.UpdateResourceAsync(publicId, moderationStatus, cancellationToken); } - /// - /// Updates details of an existing resource. - /// - /// The public ID of the resource to update. - /// The image moderation status. - /// Parsed response of the detailed resource information. - public GetResourceResult UpdateResource(string publicId, ModerationStatus moderationStatus) + /// + public Task UpdateResourceAsync(UpdateParams parameters, CancellationToken? cancellationToken = null) { - return UpdateResource(new UpdateParams(publicId) { ModerationStatus = moderationStatus }); + return cloudinaryAdmin.UpdateResourceAsync(parameters, cancellationToken); } - /// - /// Updates details of an existing resource asynchronously. - /// - /// Parameters to update details of an existing resource. - /// (Optional) Cancellation token. - /// Parsed response of the detailed resource information. - public Task UpdateResourceAsync(UpdateParams parameters, CancellationToken? cancellationToken = null) + /// + public GetResourceResult UpdateResource(string publicId, ModerationStatus moderationStatus) { - var url = GetApiUrlV(). - ResourceType("resources"). - Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). - Add(parameters.Type).Add(parameters.PublicId). - BuildUrl(); - - return CallAdminApiAsync(HttpMethod.POST, url, parameters, cancellationToken); + return cloudinaryAdmin.UpdateResource(publicId, moderationStatus); } - /// - /// Updates details of an existing resource. - /// - /// Parameters to update details of an existing resource. - /// Parsed response of the detailed resource information. + /// public GetResourceResult UpdateResource(UpdateParams parameters) { - return UpdateResourceAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.UpdateResource(parameters); } - /// - /// Gets details of a single resource as well as all its derived resources by its public ID asynchronously. - /// - /// The public ID of the resource. - /// (Optional) Cancellation token. - /// Parsed response with the detailed resource information. + /// public Task GetResourceAsync(string publicId, CancellationToken? cancellationToken = null) { - return GetResourceAsync(new GetResourceParams(publicId), cancellationToken); + return cloudinaryAdmin.GetResourceAsync(publicId, cancellationToken); } - /// - /// Gets details of a single resource as well as all its derived resources by its public ID. - /// - /// The public ID of the resource. - /// Parsed response with the detailed resource information. - public GetResourceResult GetResource(string publicId) + /// + public Task GetResourceAsync(GetResourceParams parameters, CancellationToken? cancellationToken = null) { - return GetResource(new GetResourceParams(publicId)); + return cloudinaryAdmin.GetResourceAsync(parameters, cancellationToken); } - /// - /// Gets details of the requested resource as well as all its derived resources asynchronously. - /// - /// Parameters of the request of resource. - /// (Optional) Cancellation token. - /// Parsed response with the detailed resource information. - public Task GetResourceAsync(GetResourceParams parameters, CancellationToken? cancellationToken = null) + /// + public GetResourceResult GetResource(string publicId) { - UrlBuilder urlBuilder = new UrlBuilder( - GetApiUrlV(). - ResourceType("resources"). - Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). - Add(parameters.Type). - Add(parameters.PublicId). - BuildUrl(), - parameters.ToParamsDictionary()); - - return CallAdminApiAsync( - HttpMethod.GET, - urlBuilder.ToString(), - parameters, - cancellationToken); - } - - /// - /// Gets details of the requested resource as well as all its derived resources. - /// - /// Parameters of the request of resource. - /// Parsed response with the detailed resource information. + return cloudinaryAdmin.GetResource(publicId); + } + + /// public GetResourceResult GetResource(GetResourceParams parameters) { - return GetResourceAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.GetResource(parameters); } - /// - /// Deletes all derived resources with the given IDs asynchronously. - /// - /// An array of up to 100 derived_resource_ids. - /// Parsed result of deletion derived resources. + /// public Task DeleteDerivedResourcesAsync(params string[] ids) { - var p = new DelDerivedResParams(); - p.DerivedResources.AddRange(ids); - return DeleteDerivedResourcesAsync(p); + return cloudinaryAdmin.DeleteDerivedResourcesAsync(ids); } - /// - /// Deletes all derived resources with the given IDs. - /// - /// An array of up to 100 derived_resource_ids. - /// Parsed result of deletion derived resources. - public DelDerivedResResult DeleteDerivedResources(params string[] ids) + /// + public Task DeleteDerivedResourcesAsync(DelDerivedResParams parameters, CancellationToken? cancellationToken = null) { - DelDerivedResParams p = new DelDerivedResParams(); - p.DerivedResources.AddRange(ids); - return DeleteDerivedResources(p); + return cloudinaryAdmin.DeleteDerivedResourcesAsync(parameters, cancellationToken); } - /// - /// Deletes all derived resources with the given parameters asynchronously. - /// - /// Parameters to delete derived resources. - /// (Optional) Cancellation token. - /// Parsed result of deletion derived resources. - public Task DeleteDerivedResourcesAsync(DelDerivedResParams parameters, CancellationToken? cancellationToken = null) + /// + public DelDerivedResResult DeleteDerivedResources(params string[] ids) { - var urlBuilder = new UrlBuilder( - GetApiUrlV(). - Add("derived_resources"). - BuildUrl(), - parameters.ToParamsDictionary()); - - return CallAdminApiAsync( - HttpMethod.DELETE, - urlBuilder.ToString(), - parameters, - cancellationToken); + return cloudinaryAdmin.DeleteDerivedResources(ids); } - /// - /// Deletes all derived resources with the given parameters. - /// - /// Parameters to delete derived resources. - /// Parsed result of deletion derived resources. + /// public DelDerivedResResult DeleteDerivedResources(DelDerivedResParams parameters) { - return DeleteDerivedResourcesAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.DeleteDerivedResources(parameters); } - /// - /// Deletes all resources of the given resource type and with the given public IDs asynchronously. - /// - /// The type of file to delete. Default: image. - /// Array of up to 100 public_ids. - /// Parsed result of deletion resources. + /// public Task DeleteResourcesAsync(ResourceType type, params string[] publicIds) { - var p = new DelResParams() { ResourceType = type }; - p.PublicIds.AddRange(publicIds); - return DeleteResourcesAsync(p); + return cloudinaryAdmin.DeleteResourcesAsync(type, publicIds); } - /// - /// Deletes all resources of the given resource type and with the given public IDs. - /// - /// The type of file to delete. Default: image. - /// Array of up to 100 public_ids. - /// Parsed result of deletion resources. - public DelResResult DeleteResources(ResourceType type, params string[] publicIds) + /// + public Task DeleteResourcesAsync(params string[] publicIds) { - DelResParams p = new DelResParams() { ResourceType = type }; - p.PublicIds.AddRange(publicIds); - return DeleteResources(p); + return cloudinaryAdmin.DeleteResourcesAsync(publicIds); } - /// - /// Deletes all resources with the given public IDs asynchronously. - /// - /// Array of up to 100 public_ids. - /// Parsed result of deletion resources. - public Task DeleteResourcesAsync(params string[] publicIds) + /// + public Task DeleteResourcesAsync(DelResParams parameters, CancellationToken? cancellationToken = null) { - var p = new DelResParams(); - p.PublicIds.AddRange(publicIds); - return DeleteResourcesAsync(p); + return cloudinaryAdmin.DeleteResourcesAsync(parameters, cancellationToken); } - /// - /// Deletes all resources with the given public IDs. - /// - /// Array of up to 100 public_ids. - /// Parsed result of deletion resources. + /// + public DelResResult DeleteResources(ResourceType type, params string[] publicIds) + { + return cloudinaryAdmin.DeleteResources(type, publicIds); + } + + /// public DelResResult DeleteResources(params string[] publicIds) { - DelResParams p = new DelResParams(); - p.PublicIds.AddRange(publicIds); - return DeleteResources(p); + return cloudinaryAdmin.DeleteResources(publicIds); } - /// - /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to - /// a maximum of 1000 original resources) asynchronously. - /// - /// Delete all resources where the public ID starts with the given prefix. - /// (Optional) Cancellation token. - /// Parsed result of deletion resources. - public Task DeleteResourcesByPrefixAsync(string prefix, CancellationToken? cancellationToken = null) + /// + public DelResResult DeleteResources(DelResParams parameters) { - var p = new DelResParams() { Prefix = prefix }; - return DeleteResourcesAsync(p, cancellationToken); + return cloudinaryAdmin.DeleteResources(parameters); } - /// - /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to - /// a maximum of 1000 original resources). - /// - /// Delete all resources where the public ID starts with the given prefix. - /// Parsed result of deletion resources. - public DelResResult DeleteResourcesByPrefix(string prefix) + /// + public Task DeleteResourcesByPrefixAsync(string prefix, CancellationToken? cancellationToken = null) { - DelResParams p = new DelResParams() { Prefix = prefix }; - return DeleteResources(p); + return cloudinaryAdmin.DeleteResourcesByPrefixAsync(prefix, cancellationToken); } - /// - /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to - /// a maximum of 1000 original resources) asynchronously. - /// - /// Delete all resources where the public ID starts with the given prefix. - /// If true, delete only the derived images of the matching resources. - /// Continue deletion from the given cursor. - /// (Optional) Cancellation token. - /// Parsed result of deletion resources. + /// public Task DeleteResourcesByPrefixAsync(string prefix, bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null) { - var p = new DelResParams() - { - Prefix = prefix, - KeepOriginal = keepOriginal, - NextCursor = nextCursor, - }; - return DeleteResourcesAsync(p, cancellationToken); - } - - /// - /// Deletes all resources, including derived resources, where the public ID starts with the given prefix (up to - /// a maximum of 1000 original resources). - /// - /// Delete all resources where the public ID starts with the given prefix. - /// If true, delete only the derived images of the matching resources. - /// Continue deletion from the given cursor. - /// Parsed result of deletion resources. + return cloudinaryAdmin.DeleteResourcesByPrefixAsync(prefix, keepOriginal, nextCursor, cancellationToken); + } + + /// + public DelResResult DeleteResourcesByPrefix(string prefix) + { + return cloudinaryAdmin.DeleteResourcesByPrefix(prefix); + } + + /// public DelResResult DeleteResourcesByPrefix(string prefix, bool keepOriginal, string nextCursor) { - DelResParams p = new DelResParams() { Prefix = prefix, KeepOriginal = keepOriginal, NextCursor = nextCursor }; - return DeleteResources(p); + return cloudinaryAdmin.DeleteResourcesByPrefix(prefix, keepOriginal, nextCursor); } - /// - /// Deletes resources by the given tag name asynchronously. - /// - /// - /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of - /// 1000 original resources). - /// - /// (Optional) Cancellation token. - /// Parsed result of deletion resources. + /// public Task DeleteResourcesByTagAsync(string tag, CancellationToken? cancellationToken = null) { - var p = new DelResParams() { Tag = tag }; - return DeleteResourcesAsync(p, cancellationToken); + return cloudinaryAdmin.DeleteResourcesByTagAsync(tag, cancellationToken); } - /// - /// Deletes resources by the given tag name. - /// - /// - /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of - /// 1000 original resources). - /// - /// Parsed result of deletion resources. - public DelResResult DeleteResourcesByTag(string tag) - { - DelResParams p = new DelResParams() { Tag = tag }; - return DeleteResources(p); - } - - /// - /// Deletes resources by the given tag name asynchronously. - /// - /// - /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of - /// 1000 original resources). - /// - /// If true, delete only the derived images of the matching resources. - /// Continue deletion from the given cursor. - /// (Optional) Cancellation token. - /// Parsed result of deletion resources. + /// public Task DeleteResourcesByTagAsync(string tag, bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null) { - var p = new DelResParams() - { - Tag = tag, - KeepOriginal = keepOriginal, - NextCursor = nextCursor, - }; - return DeleteResourcesAsync(p, cancellationToken); - } - - /// - /// Deletes resources by the given tag name. - /// - /// - /// Delete all resources (and their derivatives) with the given tag name (up to a maximum of - /// 1000 original resources). - /// - /// If true, delete only the derived images of the matching resources. - /// Continue deletion from the given cursor. - /// Parsed result of deletion resources. - public DelResResult DeleteResourcesByTag(string tag, bool keepOriginal, string nextCursor) + return cloudinaryAdmin.DeleteResourcesByTagAsync(tag, keepOriginal, nextCursor, cancellationToken); + } + + /// + public DelResResult DeleteResourcesByTag(string tag) { - DelResParams p = new DelResParams() { Tag = tag, KeepOriginal = keepOriginal, NextCursor = nextCursor }; - return DeleteResources(p); + return cloudinaryAdmin.DeleteResourcesByTag(tag); } - /// - /// Deletes all resources asynchronously. - /// - /// (Optional) Cancellation token. - /// Parsed result of deletion resources. - public Task DeleteAllResourcesAsync(CancellationToken? cancellationToken = null) + /// + public DelResResult DeleteResourcesByTag(string tag, bool keepOriginal, string nextCursor) { - var p = new DelResParams() { All = true }; - return DeleteResourcesAsync(p, cancellationToken); + return cloudinaryAdmin.DeleteResourcesByTag(tag, keepOriginal, nextCursor); } - /// - /// Deletes all resources. - /// - /// Parsed result of deletion resources. - public DelResResult DeleteAllResources() + /// + public Task DeleteAllResourcesAsync(CancellationToken? cancellationToken = null) { - DelResParams p = new DelResParams() { All = true }; - return DeleteResources(p); + return cloudinaryAdmin.DeleteAllResourcesAsync(cancellationToken); } - /// - /// Deletes all resources with conditions asynchronously. - /// - /// If true, delete only the derived resources. - /// - /// Value of the to continue delete from. - /// - /// (Optional) Cancellation token. - /// Parsed result of deletion resources. + /// public Task DeleteAllResourcesAsync(bool keepOriginal, string nextCursor, CancellationToken? cancellationToken = null) { - var p = new DelResParams() - { - All = true, - KeepOriginal = keepOriginal, - NextCursor = nextCursor, - }; - return DeleteResourcesAsync(p, cancellationToken); - } - - /// - /// Deletes all resources with conditions. - /// - /// If true, delete only the derived resources. - /// - /// Value of the to continue delete from. - /// - /// Parsed result of deletion resources. - public DelResResult DeleteAllResources(bool keepOriginal, string nextCursor) - { - DelResParams p = new DelResParams() { All = true, KeepOriginal = keepOriginal, NextCursor = nextCursor }; - return DeleteResources(p); + return cloudinaryAdmin.DeleteAllResourcesAsync(keepOriginal, nextCursor, cancellationToken); } - /// - /// Deletes all resources with parameters asynchronously. - /// - /// Parameters for deletion resources. - /// (Optional) Cancellation token. - /// Parsed result of deletion resources. - public Task DeleteResourcesAsync(DelResParams parameters, CancellationToken? cancellationToken = null) + /// + public DelResResult DeleteAllResources() { - var url = GetApiUrlV(). - Add("resources"). - Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)); - - url = string.IsNullOrEmpty(parameters.Tag) - ? url.Add(parameters.Type) - : url.Add("tags").Add(parameters.Tag); - - var urlBuilder = new UrlBuilder(url.BuildUrl(), parameters.ToParamsDictionary()); - - return CallAdminApiAsync( - HttpMethod.DELETE, - urlBuilder.ToString(), - parameters, - cancellationToken); + return cloudinaryAdmin.DeleteAllResources(); } - /// - /// Deletes all resources with parameters. - /// - /// Parameters for deletion resources. - /// Parsed result of deletion resources. - public DelResResult DeleteResources(DelResParams parameters) + /// + public DelResResult DeleteAllResources(bool keepOriginal, string nextCursor) { - return DeleteResourcesAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.DeleteAllResources(keepOriginal, nextCursor); } - /// - /// Restores a deleted resources by array of public ids asynchronously. - /// - /// The public IDs of (deleted or existing) backed up resources to restore. - /// Parsed result of restoring resources. + /// public Task RestoreAsync(params string[] publicIds) { - var restoreParams = new RestoreParams(); - restoreParams.PublicIds.AddRange(publicIds); - - return RestoreAsync(restoreParams); + return cloudinaryAdmin.RestoreAsync(publicIds); } - /// - /// Restores a deleted resources by array of public ids. - /// - /// The public IDs of (deleted or existing) backed up resources to restore. - /// Parsed result of restoring resources. - public RestoreResult Restore(params string[] publicIds) + /// + public Task RestoreAsync(RestoreParams parameters, CancellationToken? cancellationToken = null) { - RestoreParams restoreParams = new RestoreParams(); - restoreParams.PublicIds.AddRange(publicIds); - - return Restore(restoreParams); + return cloudinaryAdmin.RestoreAsync(parameters, cancellationToken); } - /// - /// Restores a deleted resources asynchronously. - /// - /// Parameters to restore a deleted resources. - /// (Optional) Cancellation token. - /// Parsed result of restoring resources. - public Task RestoreAsync(RestoreParams parameters, CancellationToken? cancellationToken = null) + /// + public RestoreResult Restore(params string[] publicIds) { - var url = GetApiUrlV(). - ResourceType("resources"). - Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)). - Add("upload"). - Add("restore").BuildUrl(); - - return CallAdminApiAsync(HttpMethod.POST, url, parameters, cancellationToken); + return cloudinaryAdmin.Restore(publicIds); } - /// - /// Restores a deleted resources. - /// - /// Parameters to restore a deleted resources. - /// Parsed result of restoring resources. + /// public RestoreResult Restore(RestoreParams parameters) { - return RestoreAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.Restore(parameters); } - /// - /// Returns list of all upload mappings asynchronously. - /// - /// - /// Uses only and - /// properties. Can be null. - /// - /// (Optional) Cancellation token. - /// Parsed response after Upload mappings manipulation. + /// public Task UploadMappingsAsync(UploadMappingParams parameters, CancellationToken? cancellationToken = null) { - return CallUploadMappingsApiAsync(HttpMethod.GET, parameters, cancellationToken); + return cloudinaryAdmin.UploadMappingsAsync(parameters, cancellationToken); } - /// - /// Returns list of all upload mappings. - /// - /// - /// Uses only and - /// properties. Can be null. - /// - /// Parsed response after Upload mappings manipulation. + /// public UploadMappingResults UploadMappings(UploadMappingParams parameters) { - return CallUploadMappingsApi(HttpMethod.GET, parameters); + return cloudinaryAdmin.UploadMappings(parameters); } - /// - /// Returns single upload mapping by name asynchronously. - /// - /// Folder name. - /// (Optional) Cancellation token. - /// Parsed response after Upload mappings manipulation. + /// public Task UploadMappingAsync(string folder, CancellationToken? cancellationToken = null) { - if (string.IsNullOrEmpty(folder)) - { - throw new ArgumentException("Folder name is required.", nameof(folder)); - } - - var parameters = new UploadMappingParams() { Folder = folder }; - - return CallUploadMappingsApiAsync(HttpMethod.GET, parameters, cancellationToken); + return cloudinaryAdmin.UploadMappingAsync(folder, cancellationToken); } - /// - /// Returns single upload mapping by name. - /// - /// Folder name. - /// Parsed response after Upload mappings manipulation. + /// public UploadMappingResults UploadMapping(string folder) { - if (string.IsNullOrEmpty(folder)) - { - throw new ArgumentException("Folder must be specified."); - } - - var parameters = new UploadMappingParams() { Folder = folder }; - - return CallUploadMappingsApi(HttpMethod.GET, parameters); + return cloudinaryAdmin.UploadMapping(folder); } - /// - /// Creates a new upload mapping folder and its template (URL) asynchronously. - /// - /// Folder name to create. - /// URL template for mapping to the . - /// (Optional) Cancellation token. - /// Parsed response after Upload mappings manipulation. + /// public Task CreateUploadMappingAsync(string folder, string template, CancellationToken? cancellationToken = null) { - var parameters = CreateUploadMappingParams(folder, template); - return CallUploadMappingsApiAsync(HttpMethod.POST, parameters, cancellationToken); + return cloudinaryAdmin.CreateUploadMappingAsync(folder, template, cancellationToken); } - /// - /// Creates a new upload mapping folder and its template (URL). - /// - /// Folder name to create. - /// URL template for mapping to the . - /// Parsed response after Upload mappings manipulation. + /// public UploadMappingResults CreateUploadMapping(string folder, string template) { - var parameters = CreateUploadMappingParams(folder, template); - return CallUploadMappingsApi(HttpMethod.POST, parameters); + return cloudinaryAdmin.CreateUploadMapping(folder, template); } - /// - /// Updates existing upload mapping asynchronously. - /// - /// Existing Folder to be updated. - /// New value of Template URL. - /// (Optional) Cancellation token. - /// Parsed response after Upload mappings update. + /// public Task UpdateUploadMappingAsync(string folder, string newTemplate, CancellationToken? cancellationToken = null) { - var parameters = CreateUploadMappingParams(folder, newTemplate); - return CallUploadMappingsApiAsync(HttpMethod.PUT, parameters, cancellationToken); + return cloudinaryAdmin.UpdateUploadMappingAsync(folder, newTemplate, cancellationToken); } - /// - /// Updates existing upload mapping. - /// - /// Existing Folder to be updated. - /// New value of Template URL. - /// Parsed response after Upload mappings update. + /// public UploadMappingResults UpdateUploadMapping(string folder, string newTemplate) { - var parameters = CreateUploadMappingParams(folder, newTemplate); - return CallUploadMappingsApi(HttpMethod.PUT, parameters); + return cloudinaryAdmin.UpdateUploadMapping(folder, newTemplate); } - /// - /// Deletes all upload mappings asynchronously. - /// - /// (Optional) Cancellation token. - /// Parsed response after Upload mappings delete. + /// public Task DeleteUploadMappingAsync(CancellationToken? cancellationToken = null) { - return DeleteUploadMappingAsync(string.Empty, cancellationToken); + return cloudinaryAdmin.DeleteUploadMappingAsync(cancellationToken); } - /// - /// Deletes all upload mappings. - /// - /// Parsed response after Upload mappings delete. - public UploadMappingResults DeleteUploadMapping() + /// + public Task DeleteUploadMappingAsync(string folder, CancellationToken? cancellationToken = null) { - return DeleteUploadMapping(string.Empty); + return cloudinaryAdmin.DeleteUploadMappingAsync(folder, cancellationToken); } - /// - /// Deletes upload mapping by name asynchronously. - /// - /// Folder name. - /// (Optional) Cancellation token. - /// Parsed response after Upload mappings manipulation. - public Task DeleteUploadMappingAsync(string folder, CancellationToken? cancellationToken = null) + /// + public UploadMappingResults DeleteUploadMapping() { - var parameters = new UploadMappingParams { Folder = folder }; - return CallUploadMappingsApiAsync(HttpMethod.DELETE, parameters, cancellationToken); + return cloudinaryAdmin.DeleteUploadMapping(); } - /// - /// Deletes upload mapping by name. - /// - /// Folder name. - /// Parsed response after Upload mappings manipulation. + /// public UploadMappingResults DeleteUploadMapping(string folder) { - var parameters = new UploadMappingParams { Folder = folder }; - return CallUploadMappingsApi(HttpMethod.DELETE, parameters); + return cloudinaryAdmin.DeleteUploadMapping(folder); } - /// - /// Updates Cloudinary transformation resource asynchronously. - /// - /// Parameters for transformation update. - /// (Optional) Cancellation token. - /// Parsed response after transformation manipulation. + /// public Task UpdateTransformAsync(UpdateTransformParams parameters, CancellationToken? cancellationToken = null) { - var httpMethod = HttpMethod.PUT; - var url = GetTransformationUrl(httpMethod, parameters); - - return CallAdminApiAsync(httpMethod, url, parameters, cancellationToken); + return cloudinaryAdmin.UpdateTransformAsync(parameters, cancellationToken); } - /// - /// Updates Cloudinary transformation resource. - /// - /// Parameters for transformation update. - /// Parsed response after transformation manipulation. + /// public UpdateTransformResult UpdateTransform(UpdateTransformParams parameters) { - return UpdateTransformAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.UpdateTransform(parameters); } - /// - /// Creates Cloudinary transformation resource asynchronously. - /// - /// Parameters of the new transformation. - /// (Optional) Cancellation token. - /// Parsed response after transformation manipulation. + /// public Task CreateTransformAsync(CreateTransformParams parameters, CancellationToken? cancellationToken = null) { - var httpMethod = HttpMethod.POST; - var url = GetTransformationUrl(httpMethod, parameters); - - return CallAdminApiAsync(httpMethod, url, parameters, cancellationToken); + return cloudinaryAdmin.CreateTransformAsync(parameters, cancellationToken); } - /// - /// Creates Cloudinary transformation resource. - /// - /// Parameters of the new transformation. - /// Parsed response after transformation manipulation. + /// public TransformResult CreateTransform(CreateTransformParams parameters) { - return CreateTransformAsync(parameters, null).GetAwaiter().GetResult(); + return cloudinaryAdmin.CreateTransform(parameters); } - /// - /// Deletes transformation by name asynchronously. - /// - /// The name of transformation to delete. - /// (Optional) Cancellation token. - /// Parsed response after transformation manipulation. + /// public Task DeleteTransformAsync(string transformName, CancellationToken? cancellationToken = null) { - var httpMethod = HttpMethod.DELETE; - var url = GetTransformationUrl(httpMethod, new DeleteTransformParams() { Transformation = transformName }); - - return CallAdminApiAsync( - httpMethod, - url, - null, - cancellationToken); + return cloudinaryAdmin.DeleteTransformAsync(transformName, cancellationToken); } - /// - /// Deletes transformation by name. - /// - /// The name of transformation to delete. - /// Parsed response after transformation manipulation. + /// public TransformResult DeleteTransform(string transformName) { - return DeleteTransformAsync(transformName, null).GetAwaiter().GetResult(); - } - - private static void CheckIfNotEmpty(string folder) - { - if (string.IsNullOrEmpty(folder)) - { - throw new ArgumentException("Folder must be set."); - } - } - - private static void CheckFolderParameter(string folder) - { - if (string.IsNullOrEmpty(folder)) - { - throw new ArgumentException( - "folder must be set. Please use RootFolders() to get list of folders in root."); - } - } - - private static UploadMappingParams CreateUploadMappingParams(string folder, string template) - { - if (string.IsNullOrEmpty(folder)) - { - throw new ArgumentException("Folder property must be specified."); - } - - if (string.IsNullOrEmpty(template)) - { - throw new ArgumentException("Template must be specified."); - } - - var parameters = new UploadMappingParams() - { - Folder = folder, - Template = template, - }; - return parameters; - } - - private UploadPresetApiParams PrepareUploadPresetApiParams(UploadPresetParams parameters) - { - var paramsCopy = (UploadPresetParams)parameters.Copy(); - paramsCopy.Name = null; - - var url = GetApiUrlV() - .Add("upload_presets") - .Add(parameters.Name) - .BuildUrl(); - - return new UploadPresetApiParams(HttpMethod.PUT, url, paramsCopy); - } - - private string GetFolderUrl(string folder = null, GetFoldersParams parameters = null) - { - var urlWithoutParams = GetApiUrlV().Add("folders").Add(folder).BuildUrl(); - - return (parameters != null) ? new UrlBuilder(urlWithoutParams, parameters.ToParamsDictionary()).ToString() : urlWithoutParams; - } - - private string GetUsageUrl(DateTime? date) - { - var url = GetApiUrlV().Action("usage"); - - if (date.HasValue) - { - url.Add(date.Value.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture)); - } - - return url.BuildUrl(); - } - - private string GetListResourcesUrl(ListResourcesParams parameters) - { - var url = GetResourcesUrl().Add(ApiShared.GetCloudinaryParam(parameters.ResourceType)); - - switch (parameters) - { - case ListResourcesByTagParams tagParams when !string.IsNullOrEmpty(tagParams.Tag): - url - .Add("tags") - .Add(tagParams.Tag); - - break; - case ListResourcesByModerationParams modParams when !string.IsNullOrEmpty(modParams.ModerationKind): - url - .Add("moderations") - .Add(modParams.ModerationKind) - .Add(Api.GetCloudinaryParam(modParams.ModerationStatus)); - - break; - case ListResourcesByContextParams _: - url.Add("context"); - - break; - } - - var urlBuilder = new UrlBuilder( - url.BuildUrl(), - parameters.ToParamsDictionary()); - - var s = urlBuilder.ToString(); - return s; - } - - private Task PublishResourceAsync( - string byKey, - string value, - PublishResourceParams parameters, - CancellationToken? cancellationToken) - { - if (!string.IsNullOrWhiteSpace(byKey) && !string.IsNullOrWhiteSpace(value)) - { - parameters.AddCustomParam(byKey, value); - } - - Url url = GetApiUrlV() - .Add("resources") - .Add(parameters.ResourceType.ToString().ToLowerInvariant()) - .Add("publish_resources"); - - return CallAdminApiAsync(HttpMethod.POST, url.BuildUrl(), parameters, cancellationToken); - } - - private PublishResourceResult PublishResource(string byKey, string value, PublishResourceParams parameters) - { - return PublishResourceAsync(byKey, value, parameters, null).GetAwaiter().GetResult(); - } - - private Task UpdateResourceAccessModeAsync( - string byKey, - string value, - UpdateResourceAccessModeParams parameters, - CancellationToken? cancellationToken = null) - { - if (!string.IsNullOrWhiteSpace(byKey) && !string.IsNullOrWhiteSpace(value)) - { - parameters.AddCustomParam(byKey, value); - } - - var url = GetApiUrlV() - .Add(Constants.RESOURCES_API_URL) - .Add(parameters.ResourceType.ToString().ToLowerInvariant()) - .Add(parameters.Type) - .Add(Constants.UPDATE_ACESS_MODE); - - return CallAdminApiAsync( - HttpMethod.POST, - url.BuildUrl(), - parameters, - cancellationToken); - } - - private UpdateResourceAccessModeResult UpdateResourceAccessMode(string byKey, string value, UpdateResourceAccessModeParams parameters) - { - return UpdateResourceAccessModeAsync(byKey, value, parameters).GetAwaiter().GetResult(); - } - - private Url GetResourcesUrl() => GetApiUrlV().ResourceType("resources"); - - private Task CallAdminApiAsync( - HttpMethod httpMethod, - string url, - BaseParams parameters, - CancellationToken? cancellationToken, - Dictionary extraHeaders = null) - where T : BaseResult, new() - { - return m_api.CallApiAsync( - httpMethod, - url, - parameters, - null, - extraHeaders, - cancellationToken); - } - - private string GetTransformationUrl(HttpMethod httpMethod, BaseParams parameters) - { - var url = GetApiUrlV(). - ResourceType("transformations"). - BuildUrl(); - - if (parameters != null && (httpMethod == HttpMethod.GET || httpMethod == HttpMethod.DELETE)) - { - url = new UrlBuilder(url, parameters.ToParamsDictionary()).ToString(); - } - - return url; - } - - /// - /// Calls an upload mappings API. - /// - /// HTTP method. - /// Parameters for Mapping of folders to URL prefixes for dynamic image fetching from - /// existing online locations. - /// Parsed response after Upload mappings manipulation. - private UploadMappingResults CallUploadMappingsApi(HttpMethod httpMethod, UploadMappingParams parameters) - { - return CallUploadMappingsApiAsync(httpMethod, parameters).GetAwaiter().GetResult(); - } - - /// - /// Calls an upload mappings API asynchronously. - /// - /// HTTP method. - /// Parameters for Mapping of folders to URL prefixes for dynamic image fetching from - /// existing online locations. - /// (Optional) Cancellation token. - /// Parsed response after Upload mappings manipulation. - private Task CallUploadMappingsApiAsync(HttpMethod httpMethod, UploadMappingParams parameters, CancellationToken? cancellationToken = null) - { - var url = (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) - ? GetUploadMappingUrl() - : GetUploadMappingUrl(parameters); - - return CallAdminApiAsync( - httpMethod, - url, - parameters, - cancellationToken); - } - - /// - /// Call api with specified parameters asynchronously. - /// - /// New parameters for upload preset. - /// (Optional) Cancellation token. - private Task CallApiAsync(UploadPresetApiParams apiParams, CancellationToken? cancellationToken = null) - where T : BaseResult, new() => - CallAdminApiAsync(apiParams.HttpMethod, apiParams.Url, apiParams.ParamsCopy, cancellationToken); - - /// - /// Call api with specified parameters. - /// - /// New parameters for upload preset. - private T CallApi(UploadPresetApiParams apiParams) - where T : BaseResult, new() => - CallApiAsync(apiParams).GetAwaiter().GetResult(); - - private string GetUploadMappingUrl(UploadMappingParams parameters) - { - var uri = GetUploadMappingUrl(); - return (parameters == null) ? uri : new UrlBuilder(uri, parameters.ToParamsDictionary()).ToString(); - } - - private string GetUploadMappingUrl() - { - return GetApiUrlV(). - ResourceType("upload_mappings"). - BuildUrl(); - } - - /// - /// Private helper class for specifying parameters for upload preset api call. - /// - private class UploadPresetApiParams - { - /// - /// Initializes a new instance of the class. - /// - /// Http request method. - /// Url for api call. - /// Parameters of the upload preset. - public UploadPresetApiParams( - HttpMethod httpMethod, - string url, - UploadPresetParams paramsCopy) - { - Url = url; - ParamsCopy = paramsCopy; - HttpMethod = httpMethod; - } - - /// - /// Gets url for api call. - /// - public string Url { get; private set; } - - /// - /// Gets parameters of the upload preset. - /// - public UploadPresetParams ParamsCopy { get; private set; } - - /// - /// Gets http request method. - /// - public HttpMethod HttpMethod { get; private set; } + return cloudinaryAdmin.DeleteTransform(transformName); } } } diff --git a/CloudinaryDotNet/Cloudinary.UploadApi.cs b/CloudinaryDotNet/Cloudinary.UploadApi.cs index 36e13b05..8f487b98 100644 --- a/CloudinaryDotNet/Cloudinary.UploadApi.cs +++ b/CloudinaryDotNet/Cloudinary.UploadApi.cs @@ -3,9 +3,6 @@ namespace CloudinaryDotNet using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Globalization; - using System.Linq; - using System.Net; using System.Threading; using System.Threading.Tasks; using CloudinaryDotNet.Actions; @@ -14,245 +11,111 @@ namespace CloudinaryDotNet /// Main class of Cloudinary .NET API. /// [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Reviewed.")] - public partial class Cloudinary + public partial class Cloudinary : ICloudinaryUpload { - /// - /// Resource type 'image'. - /// - protected const string RESOURCE_TYPE_IMAGE = "image"; - - /// - /// Action 'generate_archive'. - /// - protected const string ACTION_GENERATE_ARCHIVE = "generate_archive"; + private readonly ICloudinaryUpload cloudinaryUpload; - /// - /// Default chunk (buffer) size for upload large files. - /// - protected const int DEFAULT_CHUNK_SIZE = 20 * 1024 * 1024; // 20 MB - - /// - /// Uploads an image file to Cloudinary asynchronously. - /// - /// Parameters of image uploading . - /// (Optional) Cancellation token. - /// Results of image uploading. + /// public Task UploadAsync(ImageUploadParams parameters, CancellationToken? cancellationToken = null) { - return UploadAsync(parameters, cancellationToken); + return cloudinaryUpload.UploadAsync(parameters, cancellationToken); } - /// - /// Uploads an image file to Cloudinary. - /// - /// Parameters of image uploading . - /// Results of image uploading. - public ImageUploadResult Upload(ImageUploadParams parameters) + /// + public Task UploadAsync(VideoUploadParams parameters, CancellationToken? cancellationToken = null) { - return Upload(parameters); + return cloudinaryUpload.UploadAsync(parameters, cancellationToken); } - /// - /// Uploads a video file to Cloudinary asynchronously. - /// - /// Parameters of video uploading. - /// (Optional) Cancellation token. - /// Results of video uploading. - public Task UploadAsync(VideoUploadParams parameters, CancellationToken? cancellationToken = null) + /// + public Task UploadAsync(string resourceType, IDictionary parameters, FileDescription fileDescription, CancellationToken? cancellationToken = null) { - return UploadAsync(parameters, cancellationToken); + return cloudinaryUpload.UploadAsync(resourceType, parameters, fileDescription, cancellationToken); } - /// - /// Uploads a video file to Cloudinary. - /// - /// Parameters of video uploading. - /// Results of video uploading. - public VideoUploadResult Upload(VideoUploadParams parameters) + /// + public Task UploadAsync(RawUploadParams parameters, string type = "auto", CancellationToken? cancellationToken = null) { - return Upload(parameters); + return cloudinaryUpload.UploadAsync(parameters, type, cancellationToken); } - /// - /// Uploads a file to Cloudinary asynchronously. - /// - /// Resource type ("image", "raw", "video", "auto"). - /// Upload parameters. - /// File description. - /// (Optional) Cancellation token. - /// Results of the raw file uploading. - public Task UploadAsync( - string resourceType, - IDictionary parameters, - FileDescription fileDescription, - CancellationToken? cancellationToken = null) + /// + public ImageUploadResult Upload(ImageUploadParams parameters) { - var uri = GetUploadUrl(resourceType); - - fileDescription.Reset(); - - var dict = NormalizeParameters(parameters); + return cloudinaryUpload.Upload(parameters); + } - return CallUploadApiAsync(uri, dict, cancellationToken, fileDescription); + /// + public VideoUploadResult Upload(VideoUploadParams parameters) + { + return cloudinaryUpload.Upload(parameters); } - /// - /// Uploads a file to Cloudinary. - /// - /// Resource type ("image", "raw", "video", "auto"). - /// Upload parameters. - /// File description. - /// Results of the raw file uploading. + /// public RawUploadResult Upload(string resourceType, IDictionary parameters, FileDescription fileDescription) { - return UploadAsync(resourceType, parameters, fileDescription).GetAwaiter().GetResult(); + return cloudinaryUpload.Upload(resourceType, parameters, fileDescription); } - /// - /// Uploads a file to Cloudinary asynchronously. - /// - /// Parameters of file uploading. - /// The type ("raw" or "auto", last by default). - /// (Optional) Cancellation token. - /// Parsed result of the raw file uploading. - public Task UploadAsync(RawUploadParams parameters, string type = "auto", CancellationToken? cancellationToken = null) + /// + public RawUploadResult Upload(RawUploadParams parameters, string type = "auto") { - string uri = m_api.ApiUrlImgUpV.ResourceType(type).BuildUrl(); - - parameters.File.Reset(); - - return CallUploadApiAsync( - HttpMethod.POST, - uri, - parameters, - cancellationToken, - parameters.File); + return cloudinaryUpload.Upload(parameters, type); } - /// - /// Uploads a file to Cloudinary. - /// - /// Parameters of file uploading. - /// The type ("raw" or "auto", last by default). - /// Parsed result of the raw file uploading. - public RawUploadResult Upload(RawUploadParams parameters, string type = "auto") + /// + public Task UploadLargeRawAsync(BasicRawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, CancellationToken? cancellationToken = null) { - return UploadAsync(parameters, type, null).GetAwaiter().GetResult(); + return cloudinaryUpload.UploadLargeRawAsync(parameters, bufferSize, cancellationToken); } - /// - /// Uploads large file by dividing it to chunks asynchronously. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// (Optional) Cancellation token. - /// Parsed result of the large file uploading. - /// - /// Please use BasicRawUploadParams class for large raw file uploading! - /// or - /// The UploadLargeRaw method is intended to be used for large local file uploading and can't be used for - /// remote file uploading. - /// - public Task UploadLargeRawAsync( - BasicRawUploadParams parameters, - int bufferSize = DEFAULT_CHUNK_SIZE, - CancellationToken? cancellationToken = null) + /// + public RawUploadResult UploadLargeRaw(BasicRawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE) { - return UploadLargeAsync(parameters, bufferSize, cancellationToken); + return cloudinaryUpload.UploadLargeRaw(parameters, bufferSize); } - /// - /// Uploads large file to Cloudinary by dividing it to chunks. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// Parsed result of the large file uploading. - /// - /// Please use BasicRawUploadParams class for large raw file uploading! - /// or - /// The UploadLargeRaw method is intended to be used for large local file uploading and can't be used for remote file uploading. - /// - public RawUploadResult UploadLargeRaw(BasicRawUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + /// + public Task UploadLargeAsync(RawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, CancellationToken? cancellationToken = null) { - return UploadLarge(parameters, bufferSize); + return cloudinaryUpload.UploadLargeAsync(parameters, bufferSize, cancellationToken); } - /// - /// Uploads large raw file to Cloudinary by dividing it to chunks asynchronously. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// (Optional) Cancellation token. - /// Parsed result of uploading. - public Task UploadLargeAsync( - RawUploadParams parameters, - int bufferSize = DEFAULT_CHUNK_SIZE, - CancellationToken? cancellationToken = null) + /// + public Task UploadLargeAsync(ImageUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, CancellationToken? cancellationToken = null) { - return UploadLargeAsync(parameters, bufferSize, cancellationToken); + return cloudinaryUpload.UploadLargeAsync(parameters, bufferSize, cancellationToken); } - /// - /// Uploads large raw file to Cloudinary by dividing it to chunks. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// Parsed result of uploading. - public RawUploadResult UploadLarge(RawUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + /// + public Task UploadLargeAsync(VideoUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, CancellationToken? cancellationToken = null) { - return UploadLarge(parameters, bufferSize); + return cloudinaryUpload.UploadLargeAsync(parameters, bufferSize, cancellationToken); } - /// - /// Uploads large image file to Cloudinary by dividing it to chunks asynchronously. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// (Optional) Cancellation token. - /// Parsed result of uploading. - public Task UploadLargeAsync( - ImageUploadParams parameters, - int bufferSize = DEFAULT_CHUNK_SIZE, - CancellationToken? cancellationToken = null) + /// + public Task UploadLargeAsync(BasicRawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, CancellationToken? cancellationToken = null) + where T : UploadResult, new() { - return UploadLargeAsync(parameters, bufferSize, cancellationToken); + return cloudinaryUpload.UploadLargeAsync(parameters, bufferSize, cancellationToken); } - /// - /// Uploads large image file to Cloudinary by dividing it to chunks. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// Parsed result of uploading. - public ImageUploadResult UploadLarge(ImageUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + /// + public RawUploadResult UploadLarge(RawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE) { - return UploadLarge(parameters, bufferSize); + return cloudinaryUpload.UploadLarge(parameters, bufferSize); } - /// - /// Uploads large video file to Cloudinary by dividing it to chunks asynchronously. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// (Optional) Cancellation token. - /// Parsed result of uploading. - public Task UploadLargeAsync( - VideoUploadParams parameters, - int bufferSize = DEFAULT_CHUNK_SIZE, - CancellationToken? cancellationToken = null) + /// + public ImageUploadResult UploadLarge(ImageUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE) { - return UploadLargeAsync(parameters, bufferSize, cancellationToken); + return cloudinaryUpload.UploadLarge(parameters, bufferSize); } - /// - /// Uploads large video file to Cloudinary by dividing it to chunks. - /// - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// Parsed result of uploading. - public VideoUploadResult UploadLarge(VideoUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) + /// + public VideoUploadResult UploadLarge(VideoUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE) { - return UploadLarge(parameters, bufferSize); + return cloudinaryUpload.UploadLarge(parameters, bufferSize); } /// @@ -262,862 +125,235 @@ public VideoUploadResult UploadLarge(VideoUploadParams parameters, int bufferSiz /// Chunk (buffer) size (20 MB by default). /// Whether the file is raw. /// Parsed result of uploading. - [Obsolete("Use UploadLarge(parameters, bufferSize) instead.")] - public UploadResult UploadLarge(BasicRawUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE, bool isRaw = false) + [Obsolete("Use UploadLarge(parameters, bufferSize) instead.")] + public UploadResult UploadLarge(BasicRawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE, bool isRaw = false) { - if (isRaw) - { - return UploadLarge(parameters, bufferSize); - } - else - { - return UploadLarge(parameters, bufferSize); - } + return isRaw + ? UploadLarge(parameters, bufferSize) + : UploadLarge(parameters, bufferSize); } - /// - /// Uploads large resources to Cloudinary by dividing it to chunks asynchronously. - /// - /// The type of result of upload. - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// (Optional) Cancellation token. - /// Parsed result of uploading. - public async Task UploadLargeAsync( - BasicRawUploadParams parameters, - int bufferSize = DEFAULT_CHUNK_SIZE, - CancellationToken? cancellationToken = null) + /// + public T UploadLarge(BasicRawUploadParams parameters, int bufferSize = CloudinaryUpload.DEFAULT_CHUNK_SIZE) where T : UploadResult, new() { - CheckUploadParameters(parameters); - - if (parameters.File.IsRemote) - { - return await UploadAsync(parameters).ConfigureAwait(false); - } - - var internalParams = new UploadLargeParams(parameters, bufferSize, m_api); - T result = null; - - while (!parameters.File.Eof) - { - UpdateContentRange(internalParams); - result = await CallUploadApiAsync( - HttpMethod.POST, - internalParams.Url, - parameters, - cancellationToken, - parameters.File, - internalParams.Headers).ConfigureAwait(false); - CheckUploadResult(result); - } - - return result; + return cloudinaryUpload.UploadLarge(parameters, bufferSize); } - /// - /// Uploads large resources to Cloudinary by dividing it to chunks. - /// - /// The type of result of upload. - /// Parameters of file uploading. - /// Chunk (buffer) size (20 MB by default). - /// Parsed result of uploading. - public T UploadLarge(BasicRawUploadParams parameters, int bufferSize = DEFAULT_CHUNK_SIZE) - where T : UploadResult, new() + /// + public Task RenameAsync(string fromPublicId, string toPublicId, bool overwrite = false, CancellationToken? cancellationToken = null) { - return UploadLargeAsync(parameters, bufferSize).GetAwaiter().GetResult(); + return cloudinaryUpload.RenameAsync(fromPublicId, toPublicId, overwrite, cancellationToken); } - /// - /// Changes public identifier of a file asynchronously. - /// - /// Old identifier. - /// New identifier. - /// Overwrite a file with the same identifier as new if such file exists. - /// (Optional) Cancellation token. - /// Result of resource renaming. - public Task RenameAsync( - string fromPublicId, - string toPublicId, - bool overwrite = false, - CancellationToken? cancellationToken = null) + /// + public Task RenameAsync(RenameParams parameters, CancellationToken? cancellationToken = null) { - return RenameAsync( - new RenameParams(fromPublicId, toPublicId) - { - Overwrite = overwrite, - }, - cancellationToken); + return cloudinaryUpload.RenameAsync(parameters, cancellationToken); } - /// - /// Changes public identifier of a file. - /// - /// Old identifier. - /// New identifier. - /// Overwrite a file with the same identifier as new if such file exists. - /// Result of resource renaming. + /// public RenameResult Rename(string fromPublicId, string toPublicId, bool overwrite = false) { - var renameParams = new RenameParams(fromPublicId, toPublicId) - { - Overwrite = overwrite, - }; - - return RenameAsync(renameParams).GetAwaiter().GetResult(); - } - - /// - /// Changes public identifier of a file asynchronously. - /// - /// Operation parameters. - /// (Optional) Cancellation token. - /// Result of resource renaming. - public Task RenameAsync(RenameParams parameters, CancellationToken? cancellationToken = null) - { - var uri = GetRenameUrl(parameters); - return CallUploadApiAsync( - HttpMethod.POST, - uri, - parameters, - cancellationToken); + return cloudinaryUpload.Rename(fromPublicId, toPublicId, overwrite); } - /// - /// Changes public identifier of a file. - /// - /// Operation parameters. - /// Result of resource renaming. + /// public RenameResult Rename(RenameParams parameters) { - return RenameAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.Rename(parameters); } - /// - /// Delete file from Cloudinary asynchronously. - /// - /// Parameters for deletion of resource from Cloudinary. - /// Results of deletion. + /// public Task DestroyAsync(DeletionParams parameters) { - string uri = m_api.ApiUrlImgUpV.ResourceType( - ApiShared.GetCloudinaryParam(parameters.ResourceType)). - Action("destroy").BuildUrl(); - - return CallUploadApiAsync(HttpMethod.POST, uri, parameters, null); + return cloudinaryUpload.DestroyAsync(parameters); } - /// - /// Deletes file from Cloudinary. - /// - /// Parameters for deletion of resource from Cloudinary. - /// Results of deletion. + /// public DeletionResult Destroy(DeletionParams parameters) { - return DestroyAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.Destroy(parameters); } - /// - /// Creates and returns an URL that allows downloading the backed-up asset - /// based on the the asset ID and the version ID. - /// - /// ID of the asset. - /// Version ID of the asset. - /// Url for downloading the backed-up asset. + /// public string DownloadBackedUpAsset(string assetId, string versionId) { - Utils.ShouldNotBeEmpty(() => assetId); - Utils.ShouldNotBeEmpty(() => versionId); - - var parameters = new SortedDictionary - { - { "asset_id", assetId }, - { "version_id", versionId }, - }; - - var urlBuilder = new UrlBuilder(GetApiUrlV().Action("download_backup").BuildUrl()); - return GetDownloadUrl(urlBuilder, parameters); + return cloudinaryUpload.DownloadBackedUpAsset(assetId, versionId); } - /// - /// Manage tag assignments asynchronously. - /// - /// Parameters of tag management. - /// (Optional) Cancellation token. - /// Results of tags management. + /// public Task TagAsync(TagParams parameters, CancellationToken? cancellationToken = null) { - string uri = GetApiUrlV() - .ResourceType(Api.GetCloudinaryParam(parameters.ResourceType)) - .Action(Constants.TAGS_MANGMENT) - .BuildUrl(); - - return CallUploadApiAsync(HttpMethod.POST, uri, parameters, cancellationToken); + return cloudinaryUpload.TagAsync(parameters, cancellationToken); } - /// - /// Manages tag assignments. - /// - /// Parameters of tag management. - /// Results of tags management. + /// public TagResult Tag(TagParams parameters) { - return TagAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.Tag(parameters); } - /// - /// Manages context assignments asynchronously. - /// - /// Parameters of context management. - /// (Optional) Cancellation token. - /// Results of contexts management. + /// public Task ContextAsync(ContextParams parameters, CancellationToken? cancellationToken = null) { - string uri = m_api.ApiUrlImgUpV.ResourceType(ApiShared.GetCloudinaryParam(parameters.ResourceType)).Action(Constants.CONTEXT_MANAGMENT).BuildUrl(); - - return CallUploadApiAsync( - HttpMethod.POST, - uri, - parameters, - cancellationToken); + return cloudinaryUpload.ContextAsync(parameters, cancellationToken); } - /// - /// Manages context assignments. - /// - /// Parameters of context management. - /// Results of contexts management. + /// public ContextResult Context(ContextParams parameters) { - return ContextAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.Context(parameters); } - /// - /// This method can be used to force refresh facebook and twitter profile pictures. The response of this method - /// includes the image's version. Use this version to bypass previously cached CDN copies. Also it can be used - /// to generate transformed versions of an uploaded image. This is useful when Strict Transformations are - /// allowed for your account and you wish to create custom derived images for already uploaded images asynchronously. - /// - /// The parameters for explicit method. - /// (Optional) Cancellation token. - /// Parsed response after a call of Explicit method. + /// public Task ExplicitAsync(ExplicitParams parameters, CancellationToken? cancellationToken = null) { - string uri = GetApiUrlV() - .ResourceType(Api.GetCloudinaryParam(parameters.ResourceType)) - .Action("explicit") - .BuildUrl(); - - return CallUploadApiAsync( - HttpMethod.POST, - uri, - parameters, - cancellationToken); + return cloudinaryUpload.ExplicitAsync(parameters, cancellationToken); } - /// - /// This method can be used to force refresh facebook and twitter profile pictures. The response of this method - /// includes the image's version. Use this version to bypass previously cached CDN copies. Also it can be used - /// to generate transformed versions of an uploaded image. This is useful when Strict Transformations are - /// allowed for your account and you wish to create custom derived images for already uploaded images. - /// - /// The parameters for explicit method. - /// Parsed response after a call of Explicit method. + /// public ExplicitResult Explicit(ExplicitParams parameters) { - return ExplicitAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.Explicit(parameters); } - /// - /// Explodes multipage document to single pages asynchronously. - /// - /// Parameters of explosion operation. - /// (Optional) Cancellation token. - /// Parsed response after a call of Explode method. + /// public Task ExplodeAsync(ExplodeParams parameters, CancellationToken? cancellationToken = null) { - var url = m_api.ApiUrlImgUpV. - Action("explode"). - BuildUrl(); - - return CallUploadApiAsync( - HttpMethod.POST, - url, - parameters, - cancellationToken); + return cloudinaryUpload.ExplodeAsync(parameters, cancellationToken); } - /// - /// Explodes multipage document to single pages. - /// - /// Parameters of explosion operation. - /// Parsed response after a call of Explode method. + /// public ExplodeResult Explode(ExplodeParams parameters) { - return ExplodeAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.Explode(parameters); } - /// - /// Creates a zip archive and stores it as a raw resource in your Cloudinary account asynchronously. - /// - /// Parameters of the new generated zip archive. - /// (Optional) Cancellation token. - /// Parsed result of creating the archive. + /// public Task CreateZipAsync(ArchiveParams parameters, CancellationToken? cancellationToken = null) { - parameters.TargetFormat(ArchiveFormat.Zip); - return CreateArchiveAsync(parameters, cancellationToken); + return cloudinaryUpload.CreateZipAsync(parameters, cancellationToken); } - /// - /// Creates a zip archive and stores it as a raw resource in your Cloudinary account. - /// - /// Parameters of the new generated zip archive. - /// Parsed result of creating the archive. + /// public ArchiveResult CreateZip(ArchiveParams parameters) { - parameters.TargetFormat(ArchiveFormat.Zip); - return CreateArchive(parameters); + return cloudinaryUpload.CreateZip(parameters); } - /// - /// Creates archive and stores it as a raw resource in your Cloudinary account asynchronously. - /// - /// Parameters of new generated archive. - /// (Optional) Cancellation token. - /// Parsed result of creating the archive. + /// public Task CreateArchiveAsync(ArchiveParams parameters, CancellationToken? cancellationToken = null) { - Url url = GetApiUrlV().ResourceType(RESOURCE_TYPE_IMAGE).Action(ACTION_GENERATE_ARCHIVE); - - if (!string.IsNullOrEmpty(parameters.ResourceType())) - { - url.ResourceType(parameters.ResourceType()); - } - - parameters.Mode(ArchiveCallMode.Create); - return CallUploadApiAsync( - HttpMethod.POST, - url.BuildUrl(), - parameters, - cancellationToken); + return cloudinaryUpload.CreateArchiveAsync(parameters, cancellationToken); } - /// - /// Creates archive and stores it as a raw resource in your Cloudinary account. - /// - /// Parameters of new generated archive. - /// Parsed result of creating the archive. + /// public ArchiveResult CreateArchive(ArchiveParams parameters) { - return CreateArchiveAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.CreateArchive(parameters); } - /// - /// Returns URL on archive file. - /// - /// Parameters of generated archive. - /// URL on archive file. + /// public string DownloadArchiveUrl(ArchiveParams parameters) { - parameters.Mode(ArchiveCallMode.Download); - - UrlBuilder urlBuilder = new UrlBuilder( - GetApiUrlV(). - ResourceType(parameters.ResourceType()). - Action(ACTION_GENERATE_ARCHIVE). - BuildUrl()); - - return GetDownloadUrl(urlBuilder, parameters.ToParamsDictionary()); + return cloudinaryUpload.DownloadArchiveUrl(parameters); } - /// - /// Creates and returns an URL that when invoked creates an archive of a folder. - /// - /// Full path from the root. - /// Optional parameters of generated archive. - /// Url for downloading an archive of a folder. + /// public string DownloadFolder(string folderPath, ArchiveParams parameters = null) { - var downloadParameters = parameters ?? new ArchiveParams(); - - downloadParameters.Prefixes(new List { folderPath }); - downloadParameters.ResourceType(Constants.RESOURCE_TYPE_ALL); - - return DownloadArchiveUrl(downloadParameters); + return cloudinaryUpload.DownloadFolder(folderPath, parameters); } - /// - /// Gets URL to download tag cloud as ZIP package. - /// - /// The tag. - /// The transformation. - /// Download URL. - /// Tag should be specified. - /// Resource type (image, video or raw) of files to include in the archive (optional). - public string DownloadZip(string tag, Transformation transform, string resourceType = RESOURCE_TYPE_IMAGE) + /// + public string DownloadZip(string tag, Transformation transform, string resourceType = CloudinaryUpload.RESOURCE_TYPE_IMAGE) { - if (string.IsNullOrEmpty(tag)) - { - throw new ArgumentException("Tag should be specified!"); - } - - var urlBuilder = new UrlBuilder( - GetApiUrlV() - .ResourceType(resourceType) - .Action("download_tag.zip") - .BuildUrl()); - - var parameters = new SortedDictionary - { - { "tag", tag }, - }; - - if (transform != null) - { - parameters.Add("transformation", transform.Generate()); - } - - return GetDownloadUrl(urlBuilder, parameters); + return cloudinaryUpload.DownloadZip(tag, transform, resourceType); } - /// - /// Gets URL to download private image. - /// - /// The image public ID. - /// Whether to download image as attachment (optional). - /// Format to download (optional). - /// The type (optional). - /// The date (UNIX time in seconds) for the URL expiration. (optional). - /// Resource type (image, video or raw) of files to include in the archive (optional). - /// Download URL. - /// publicId can't be null. - public string DownloadPrivate( - string publicId, - bool? attachment = null, - string format = "", - string type = "", - long? expiresAt = null, - string resourceType = RESOURCE_TYPE_IMAGE) + /// + public string DownloadPrivate(string publicId, bool? attachment = null, string format = "", string type = "", long? expiresAt = null, string resourceType = CloudinaryUpload.RESOURCE_TYPE_IMAGE) { - if (string.IsNullOrEmpty(publicId)) - { - throw new ArgumentException("The image public ID is missing."); - } - - var urlBuilder = new UrlBuilder( - GetApiUrlV() - .ResourceType(resourceType) - .Action("download") - .BuildUrl()); - - var parameters = new SortedDictionary - { - { "public_id", publicId }, - }; - - if (!string.IsNullOrEmpty(format)) - { - parameters.Add("format", format); - } - - if (attachment != null) - { - parameters.Add("attachment", (bool)attachment ? "true" : "false"); - } - - if (!string.IsNullOrEmpty(type)) - { - parameters.Add("type", type); - } - - if (expiresAt != null) - { - parameters.Add("expires_at", expiresAt); - } - - return GetDownloadUrl(urlBuilder, parameters); + return cloudinaryUpload.DownloadPrivate(publicId, attachment, format, type, expiresAt, resourceType); } - /// - /// Eagerly generate sprites asynchronously. - /// - /// Parameters for sprite generation. - /// (Optional) Cancellation token. - /// Parsed response with detailed information about the created sprite. + /// public Task MakeSpriteAsync(SpriteParams parameters, CancellationToken? cancellationToken = null) { - var url = m_api.ApiUrlImgUpV. - Action(Constants.ACTION_NAME_SPRITE). - BuildUrl(); - - return CallUploadApiAsync( - HttpMethod.POST, - url, - parameters, - cancellationToken); + return cloudinaryUpload.MakeSpriteAsync(parameters, cancellationToken); } - /// - /// Eagerly generates sprites. - /// - /// Parameters for sprite generation. - /// Parsed response with detailed information about the created sprite. + /// public SpriteResult MakeSprite(SpriteParams parameters) { - return MakeSpriteAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.MakeSprite(parameters); } - /// - /// Gets a signed URL to download generated sprite. - /// - /// Parameters of Sprite operation. - /// Download URL. + /// public string DownloadSprite(SpriteParams parameters) { - parameters.Mode = ArchiveCallMode.Download; - var urlBuilder = new UrlBuilder( - m_api.ApiUrlImgUpV. - Action(Constants.ACTION_NAME_SPRITE). - BuildUrl()); - - return GetDownloadUrl(urlBuilder, parameters.ToParamsDictionary()); + return cloudinaryUpload.DownloadSprite(parameters); } - /// - /// Creates a single animated GIF file from a group of images asynchronously. - /// - /// Parameters of Multi operation. - /// (Optional) Cancellation token. - /// Parsed response with detailed information about the created animated GIF. + /// public Task MultiAsync(MultiParams parameters, CancellationToken? cancellationToken = null) { - var url = m_api.ApiUrlImgUpV. - Action(Constants.ACTION_NAME_MULTI). - BuildUrl(); - - return CallUploadApiAsync( - HttpMethod.POST, - url, - parameters, - cancellationToken); + return cloudinaryUpload.MultiAsync(parameters, cancellationToken); } - /// - /// Creates a single animated GIF file from a group of images. - /// - /// Parameters of Multi operation. - /// Parsed response with detailed information about the created animated GIF. + /// public MultiResult Multi(MultiParams parameters) { - return MultiAsync(parameters).GetAwaiter().GetResult(); + return cloudinaryUpload.Multi(parameters); } - /// - /// Gets a signed URL to download animated GIF file generated through multi request. - /// - /// Parameters of Multi operation. - /// Download URL. + /// public string DownloadMulti(MultiParams parameters) { - parameters.Mode = ArchiveCallMode.Download; - var urlBuilder = new UrlBuilder( - m_api.ApiUrlImgUpV. - Action(Constants.ACTION_NAME_MULTI). - BuildUrl()); - - return GetDownloadUrl(urlBuilder, parameters.ToParamsDictionary()); + return cloudinaryUpload.DownloadMulti(parameters); } - /// - /// Generate an image of a given textual string asynchronously. - /// - /// Text to draw. - /// (Optional) Cancellation token. - /// Results of generating an image of a given textual string. + /// public Task TextAsync(string text, CancellationToken? cancellationToken = null) { - return TextAsync(new TextParams(text), cancellationToken); + return cloudinaryUpload.TextAsync(text, cancellationToken); } - /// - /// Generates an image of a given textual string. - /// - /// Text to draw. - /// Results of generating an image of a given textual string. - public TextResult Text(string text) - { - return Text(new TextParams(text)); - } - - /// - /// Generates an image of a given textual string asynchronously. - /// - /// Parameters of generating an image of a given textual string. - /// (Optional) Cancellation token. - /// Results of generating an image of a given textual string. + /// public Task TextAsync(TextParams parameters, CancellationToken? cancellationToken = null) { - string uri = m_api.ApiUrlImgUpV.Action("text").BuildUrl(); - - return CallUploadApiAsync( - HttpMethod.POST, - uri, - parameters, - cancellationToken); + return cloudinaryUpload.TextAsync(parameters, cancellationToken); } - /// - /// Creates auto-generated video slideshow. - /// - /// Parameters for generating the slideshow. - /// The public id of the generated slideshow. - public CreateSlideshowResult CreateSlideshow(CreateSlideshowParams parameters) - { - return CreateSlideshowAsync(parameters).GetAwaiter().GetResult(); - } - - /// - /// Creates auto-generated video slideshow asynchronously. - /// - /// Parameters for generating the slideshow. - /// (Optional) Cancellation token. - /// The public id of the generated slideshow. - public Task CreateSlideshowAsync(CreateSlideshowParams parameters, CancellationToken? cancellationToken = null) + /// + public TextResult Text(string text) { - string uri = m_api.ApiUrlVideoUpV.Action("create_slideshow").BuildUrl(); - - return CallUploadApiAsync( - HttpMethod.POST, - uri, - parameters, - cancellationToken); + return cloudinaryUpload.Text(text); } - /// - /// Generates an image of a given textual string. - /// - /// Parameters of generating an image of a given textual string. - /// Results of generating an image of a given textual string. + /// public TextResult Text(TextParams parameters) { - return TextAsync(parameters).GetAwaiter().GetResult(); - } - - private static SortedDictionary NormalizeParameters(IDictionary parameters) - { - if (parameters == null) - { - return new SortedDictionary(); - } - - return parameters as SortedDictionary ?? new SortedDictionary(parameters); - } - - private static void CheckUploadResult(T result) - where T : UploadResult, new() - { - if (result.StatusCode != HttpStatusCode.OK) - { - var error = result.Error != null ? result.Error.Message : "Unknown error"; - throw new Exception( - $"An error has occured while uploading file (status code: {result.StatusCode}). {error}"); - } - } - - private static void CheckUploadParameters(BasicRawUploadParams parameters) - { - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters), "Upload parameters should be defined"); - } - - if (parameters.File == null) - { - throw new ArgumentException("Parameters.File parameter should be defined"); - } - } - - private static void UpdateContentRange(UploadLargeParams internalParams) - { - var fileDescription = internalParams.Parameters.File; - var fileLength = fileDescription.GetFileLength(); - var startOffset = fileDescription.BytesSent; - var endOffset = startOffset + Math.Min(internalParams.BufferSize, fileLength - startOffset) - 1; - - internalParams.Headers["Content-Range"] = $"bytes {startOffset}-{endOffset}/{fileLength}"; - } - - private Task CallUploadApiAsync( - HttpMethod httpMethod, - string url, - BaseParams parameters, - CancellationToken? cancellationToken, - FileDescription fileDescription = null, - Dictionary extraHeaders = null) - where T : BaseResult, new() - { - return m_api.CallApiAsync( - httpMethod, - url, - parameters, - fileDescription, - extraHeaders, - cancellationToken); + return cloudinaryUpload.Text(parameters); } - private Task CallUploadApiAsync( - string url, - SortedDictionary parameters, - CancellationToken? cancellationToken, - FileDescription fileDescription = null) - { - return m_api.CallAndParseAsync( - HttpMethod.POST, - url, - parameters, - fileDescription, - null, - cancellationToken); - } - - private string GetUploadUrl(string resourceType) - { - return GetApiUrlV().Action(Constants.ACTION_NAME_UPLOAD).ResourceType(resourceType).BuildUrl(); - } - - private string GetRenameUrl(RenameParams parameters) => - m_api - .ApiUrlImgUpV - .ResourceType(ApiShared.GetCloudinaryParam(parameters.ResourceType)) - .Action("rename") - .BuildUrl(); - - private string CheckUploadParametersAndGetUploadUrl(BasicRawUploadParams parameters) - { - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters), "Upload parameters should be defined"); - } - - string uri = GetApiUrlV() - .Action(Constants.ACTION_NAME_UPLOAD) - .ResourceType(ApiShared.GetCloudinaryParam(parameters.ResourceType)) - .BuildUrl(); - - parameters.File.Reset(); - return uri; - } - - /// - /// Uploads a resource to Cloudinary. - /// - /// Parameters of uploading . - /// Results of uploading. - private T Upload(TP parameters) - where T : UploadResult, new() - where TP : BasicRawUploadParams, new() - { - return UploadAsync(parameters, null).GetAwaiter().GetResult(); - } - - /// - /// Uploads a resource to Cloudinary asynchronously. - /// - /// Parameters of uploading . - /// (Optional) Cancellation token. - /// Results of uploading. - private Task UploadAsync(BasicRawUploadParams parameters, CancellationToken? cancellationToken = null) - where T : UploadResult, new() + /// + public CreateSlideshowResult CreateSlideshow(CreateSlideshowParams parameters) { - var uri = CheckUploadParametersAndGetUploadUrl(parameters); - - return CallUploadApiAsync( - HttpMethod.POST, - uri, - parameters, - cancellationToken, - parameters.File, - null); + return cloudinaryUpload.CreateSlideshow(parameters); } - private string GetDownloadUrl(UrlBuilder builder, IDictionary parameters) + /// + public Task CreateSlideshowAsync(CreateSlideshowParams parameters, CancellationToken? cancellationToken = null) { - m_api.FinalizeUploadParameters(parameters); - builder.SetParameters(parameters); - return builder.ToString(); + return cloudinaryUpload.CreateSlideshowAsync(parameters, cancellationToken); } - /// - /// Upload large file parameters. - /// - internal class UploadLargeParams + /// + public string GetCloudinaryJsConfig(bool directUpload = false, string dir = "") { - /// - /// Initializes a new instance of the class. - /// - /// Basic raw upload parameters. - /// Buffer size. - /// Technological layer to work with cloudinary API. - public UploadLargeParams(BasicRawUploadParams parameters, int bufferSize, Api api) - { - parameters.File.Reset(bufferSize); - this.Parameters = parameters; - this.Url = GetUploadUrl(parameters, api); - this.BufferSize = bufferSize; - } - - /// - /// Gets buffer size. - /// - public int BufferSize { get; } - - /// - /// Gets url. - /// - public string Url { get; } - - /// - /// Gets basic raw upload parameters. - /// - public BasicRawUploadParams Parameters { get; } - - /// - /// Gets request headers. - /// - public Dictionary Headers { get; } = new Dictionary - { - ["X-Unique-Upload-Id"] = RandomPublicId(), - }; - - /// - /// Generate random PublicId. - /// - /// Randomly generated PublicId. - private static string RandomPublicId() - { - var buffer = new byte[8]; - new Random().NextBytes(buffer); - return string.Concat(buffer.Select(x => x.ToString("X2", CultureInfo.InvariantCulture)).ToArray()); - } - - /// - /// A convenient method for uploading an image before testing. - /// - /// Parameters of type BasicRawUploadParams. - /// Action to set custom upload parameters. - /// The upload url. - private static string GetUploadUrl(BasicRawUploadParams parameters, Api mApi) - { - var url = mApi.ApiUrlImgUpV; - var name = Enum.GetName(typeof(ResourceType), parameters.ResourceType); - if (name != null) - { - url.ResourceType(name.ToLowerInvariant()); - } - - return url.BuildUrl(); - } + return cloudinaryUpload.GetCloudinaryJsConfig(directUpload, dir); } } } diff --git a/CloudinaryDotNet/Cloudinary.cs b/CloudinaryDotNet/Cloudinary.cs index d5dd505a..47138006 100644 --- a/CloudinaryDotNet/Cloudinary.cs +++ b/CloudinaryDotNet/Cloudinary.cs @@ -11,18 +11,14 @@ [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Reviewed.")] public partial class Cloudinary { - /// - /// Cloudinary object. - /// - protected Api m_api; - /// /// Initializes a new instance of the class. /// Default parameterless constructor. Assumes that environment variable CLOUDINARY_URL is set. /// public Cloudinary() { - m_api = new Api(); + cloudinaryUpload = new CloudinaryUpload(); + cloudinaryAdmin = new CloudinaryAdmin(); } /// @@ -31,7 +27,8 @@ public Cloudinary() /// Cloudinary URL. public Cloudinary(string cloudinaryUrl) { - m_api = new Api(cloudinaryUrl); + cloudinaryUpload = new CloudinaryUpload(cloudinaryUrl); + cloudinaryAdmin = new CloudinaryAdmin(cloudinaryUrl); } /// @@ -40,91 +37,8 @@ public Cloudinary(string cloudinaryUrl) /// Cloudinary account. public Cloudinary(Account account) { - m_api = new Api(account); - } - - /// - /// Gets API object that used by this instance. - /// - public Api Api - { - get { return m_api; } - } - - /// - /// Gets java script that configures Cloudinary JS. - /// - /// Whether to reference additional scripts that are necessary for uploading files directly from browser. - /// Override location of js files (default: ~/Scripts). - /// HTML script tag with Cloudinary JS configuration. - public string GetCloudinaryJsConfig(bool directUpload = false, string dir = "") - { - if (string.IsNullOrEmpty(dir)) - { - dir = "/Scripts"; - } - - StringBuilder sb = new StringBuilder(1000); - - AppendScriptLine(sb, dir, "jquery.ui.widget.js"); - AppendScriptLine(sb, dir, "jquery.iframe-transport.js"); - AppendScriptLine(sb, dir, "jquery.fileupload.js"); - AppendScriptLine(sb, dir, "jquery.cloudinary.js"); - - if (directUpload) - { - AppendScriptLine(sb, dir, "canvas-to-blob.min.js"); - AppendScriptLine(sb, dir, "jquery.fileupload-image.js"); - AppendScriptLine(sb, dir, "jquery.fileupload-process.js"); - AppendScriptLine(sb, dir, "jquery.fileupload-validate.js"); - AppendScriptLine(sb, dir, "load-image.min.js"); - } - - var cloudinaryParams = new JObject( - new JProperty[] - { - new JProperty("cloud_name", m_api.Account.Cloud), - new JProperty("api_key", m_api.Account.ApiKey), - new JProperty("private_cdn", m_api.UsePrivateCdn), - new JProperty("cdn_subdomain", m_api.CSubDomain), - }); - - if (!string.IsNullOrEmpty(m_api.PrivateCdn)) - { - cloudinaryParams.Add("secure_distribution", m_api.PrivateCdn); - } - - sb.AppendLine(""); - - return sb.ToString(); - } - - private static void AppendScriptLine(StringBuilder sb, string dir, string script) - { - sb.Append(""); - } - - /// - /// Get default API URL with version. - /// - /// URL of the API. - private Url GetApiUrlV() - { - return m_api.ApiUrlV; + cloudinaryUpload = new CloudinaryUpload(account); + cloudinaryAdmin = new CloudinaryAdmin(account); } } }