diff --git a/CHANGELOG.md b/CHANGELOG.md index 0abd0ab..01347f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## [v1.3.0](https://github.com/contentstack/contentstack-management-dotnet/tree/v1.3.0)(2026-12-04) + + - **New** + - **Taxonomy publish, localize and unlocalize**: `Taxonomy.Publish` / `PublishAsync` (collection-level; a 2xx means accepted, not completed), and `Unlocalize` / `UnlocalizeAsync` (required locale, 204 empty body). (DX-10479) + ## [v1.2.0](https://github.com/contentstack/contentstack-management-dotnet/tree/v1.2.0)(2026-11-12) - **New** diff --git a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack017_TaxonomyTest.cs b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack017_TaxonomyTest.cs index c439f38..dbe9e65 100644 --- a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack017_TaxonomyTest.cs +++ b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack017_TaxonomyTest.cs @@ -6492,6 +6492,274 @@ public void Test279_Should_Handle_Extreme_Boundary_Combinations() } } + // Taxonomy publish / unlocalize. Every named resource (locale, environment, + // branch) is looked up first; locales and environments are created here when the stack + // has too few, and those are deleted in the test's finally block. Branches are never created. + + private JsonArray QueryArrayOrEmpty(ContentstackResponse response, string key, string queryName) + { + AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Query {queryName} failed: {response.OpenResponse()}", "Query" + queryName + "Success"); + var jobj = response.OpenJsonObjectResponse(); + return (jobj?[key] ?? jobj?["items"]) as JsonArray ?? new JsonArray(); + } + + private List ResolveLocaleCodes(int count, List createdLocales) + { + var codes = new List(); + var array = QueryArrayOrEmpty(_stack.Locale().Query().Find(), "locales", "Locales"); + foreach (var item in array) + { + var code = item?["code"]?.ToString(); + if (string.IsNullOrEmpty(code) || string.Equals(code, "en-us", StringComparison.OrdinalIgnoreCase)) continue; + if (codes.Count < count) codes.Add(code); + } + string[] candidates = { "hi-in", "mr-in" }; + string[] candidateNames = { "Hindi (India)", "Marathi (India)" }; + for (int i = 0; codes.Count < count && i < candidates.Length; i++) + { + if (codes.Contains(candidates[i])) continue; + ContentstackResponse createResponse = _stack.Locale().Create(new LocaleModel + { + Code = candidates[i], + Name = candidateNames[i] + }); + AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, $"Create locale {candidates[i]} failed: {createResponse.OpenResponse()}", "CreateLocaleSuccess"); + createdLocales.Add(candidates[i]); + codes.Add(candidates[i]); + } + AssertLogger.IsTrue(codes.Count == count, $"Expected {count} non-master locale(s), resolved {codes.Count}", "ResolvedLocaleCount"); + return codes; + } + + private List ResolveEnvironmentNames(int count, List createdEnvironments) + { + var names = new List(); + var array = QueryArrayOrEmpty(_stack.Environment().Query().Find(), "environments", "Environments"); + foreach (var item in array) + { + var name = item?["name"]?.ToString(); + if (string.IsNullOrEmpty(name)) continue; + if (names.Count < count) names.Add(name); + } + while (names.Count < count) + { + string name = "tax_pub_env_" + Guid.NewGuid().ToString("N").Substring(0, 8); + ContentstackResponse createResponse = _stack.Environment().Create(new EnvironmentModel + { + Name = name, + Urls = new List + { + new LocalesUrl { Locale = "en-us", Url = "https://example.com" } + } + }); + AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, $"Create environment failed: {createResponse.OpenResponse()}", "CreateEnvironmentSuccess"); + createdEnvironments.Add(name); + names.Add(name); + } + return names; + } + + // The taxonomy, locale and environment fixtures live on the stack's own configured branch, so the + // publish must name that branch (or "main" when none is configured); it is looked up, never created. + private string ResolvePublishBranchUid() + { + string branchUid = string.IsNullOrWhiteSpace(_stack.BranchUid) ? "main" : _stack.BranchUid; + ContentstackResponse response = _stack.Branch(branchUid).Fetch(); + if (!response.IsSuccessStatusCode) + { + AssertLogger.Inconclusive($"Branch '{branchUid}' not found on the stack; skipping taxonomy publish-with-branch test."); + } + return branchUid; + } + + private string CreatePublishFixtureTaxonomy(List createdTaxonomies) + { + string taxonomyUid = "tax_pub_taxonomy_" + Guid.NewGuid().ToString("N").Substring(0, 8); + ContentstackResponse createResponse = _stack.Taxonomy().Create(new TaxonomyModel + { + Uid = taxonomyUid, + Name = "Publish Fixture Taxonomy", + Description = "Fixture for publish and unlocalize tests" + }); + AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, $"Create taxonomy failed: {createResponse.OpenResponse()}", "CreateFixtureTaxonomySuccess"); + createdTaxonomies.Add(taxonomyUid); + return taxonomyUid; + } + + private void DeleteTaxonomyPublishFixtures(List taxonomies, List environments, List locales) + { + foreach (var uid in taxonomies) + { + try { _stack.Taxonomy(uid).Delete(); } + catch (Exception ex) { Console.WriteLine($"[Cleanup] Failed to delete taxonomy {uid}: {ex.Message}"); } + } + foreach (var name in environments) + { + try { _stack.Environment(name).Delete(); } + catch (Exception ex) { Console.WriteLine($"[Cleanup] Failed to delete environment {name}: {ex.Message}"); } + } + foreach (var code in locales) + { + try { _stack.Locale(code).Delete(); } + catch (Exception ex) { Console.WriteLine($"[Cleanup] Failed to delete locale {code}: {ex.Message}"); } + } + } + + private static void AssertPublishAcknowledged(ContentstackResponse response, string name) + { + AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Publish failed: {response.OpenResponse()}", name + "Success"); + var jobj = response.OpenJsonObjectResponse(); + AssertLogger.IsNotNull(jobj?["notice"], "Publish acknowledgement notice", name + "Notice"); + AssertLogger.IsNotNull(jobj?["job_id"], "Publish acknowledgement job id", name + "JobId"); + } + + // Localizes the fixture into each locale first: publishing to a locale the taxonomy is not localized to fails + // with NOT_LOCALIZED, and unlocalizing needs a localized taxonomy to remove. + private void LocalizeFixtureToLocales(string taxonomyUid, List localeCodes) + { + foreach (string localeCode in localeCodes) + { + var localizeParams = new ParameterCollection(); + localizeParams.Add("locale", localeCode); + var localizeModel = new TaxonomyModel { Uid = taxonomyUid, Name = "Publish Localized", Description = "Localized for publish test" }; + ContentstackResponse localizeResponse = _stack.Taxonomy(taxonomyUid).Localize(localizeModel, localizeParams); + AssertLogger.IsTrue(localizeResponse.IsSuccessStatusCode, $"Localize failed: {localizeResponse.OpenResponse()}", "LocalizeFixtureSuccess"); + } + } + + private async Task PublishToLocalesAndEnvironmentsAsync(string scenario, string assertName, int count, Func> publish) + { + TestOutputLogger.LogContext("TestScenario", scenario); + var taxonomies = new List(); + var environments = new List(); + var locales = new List(); + try + { + string taxonomyUid = CreatePublishFixtureTaxonomy(taxonomies); + var localeCodes = ResolveLocaleCodes(count, locales); + LocalizeFixtureToLocales(taxonomyUid, localeCodes); + var environmentNames = ResolveEnvironmentNames(count, environments); + TestOutputLogger.LogContext("TaxonomyUid", taxonomyUid); + var model = new TaxonomyPublishModel + { + Locales = localeCodes, + Environments = environmentNames, + Items = new List { new TaxonomyPublishItem { Uid = taxonomyUid } } + }; + ContentstackResponse response = await publish(model); + AssertPublishAcknowledged(response, assertName); + } + finally + { + DeleteTaxonomyPublishFixtures(taxonomies, environments, locales); + } + } + + [TestMethod] + [DoNotParallelize] + public void Test280_Should_Publish_Taxonomy_To_One_Environment_And_Locale() + { + PublishToLocalesAndEnvironmentsAsync("Test280_Should_Publish_Taxonomy_To_One_Environment_And_Locale", "PublishOneEnvLocale", 1, + model => Task.FromResult(_stack.Taxonomy().Publish(model))).GetAwaiter().GetResult(); + } + + [TestMethod] + [DoNotParallelize] + public async Task Test281_Should_Publish_Taxonomy_To_One_Environment_And_Locale_Async() + { + await PublishToLocalesAndEnvironmentsAsync("Test281_Should_Publish_Taxonomy_To_One_Environment_And_Locale_Async", "PublishOneEnvLocaleAsync", 1, + model => _stack.Taxonomy().PublishAsync(model)); + } + + [TestMethod] + [DoNotParallelize] + public void Test282_Should_Publish_Taxonomy_To_Multiple_Locales_And_Environments() + { + PublishToLocalesAndEnvironmentsAsync("Test282_Should_Publish_Taxonomy_To_Multiple_Locales_And_Environments", "PublishMultiLocaleEnv", 2, + model => Task.FromResult(_stack.Taxonomy().Publish(model))).GetAwaiter().GetResult(); + } + + [TestMethod] + [DoNotParallelize] + public void Test283_Should_Publish_Taxonomy_With_Branch() + { + TestOutputLogger.LogContext("TestScenario", "Test283_Should_Publish_Taxonomy_With_Branch"); + string branchUid = ResolvePublishBranchUid(); + var taxonomies = new List(); + var environments = new List(); + var locales = new List(); + try + { + string taxonomyUid = CreatePublishFixtureTaxonomy(taxonomies); + var localeCodes = ResolveLocaleCodes(1, locales); + LocalizeFixtureToLocales(taxonomyUid, localeCodes); + var environmentNames = ResolveEnvironmentNames(1, environments); + TestOutputLogger.LogContext("TaxonomyUid", taxonomyUid); + TestOutputLogger.LogContext("BranchUid", branchUid); + var model = new TaxonomyPublishModel + { + Locales = localeCodes, + Environments = environmentNames, + Items = new List { new TaxonomyPublishItem { Uid = taxonomyUid } }, + Branch = branchUid + }; + ContentstackResponse response = _stack.Taxonomy().Publish(model); + AssertPublishAcknowledged(response, "PublishWithBranch"); + } + finally + { + DeleteTaxonomyPublishFixtures(taxonomies, environments, locales); + } + } + + [TestMethod] + [DoNotParallelize] + public void Test284_Should_Unlocalize_Taxonomy() + { + TestOutputLogger.LogContext("TestScenario", "Test284_Should_Unlocalize_Taxonomy"); + var taxonomies = new List(); + var locales = new List(); + try + { + string taxonomyUid = CreatePublishFixtureTaxonomy(taxonomies); + var localeCodes = ResolveLocaleCodes(1, locales); + TestOutputLogger.LogContext("TaxonomyUid", taxonomyUid); + LocalizeFixtureToLocales(taxonomyUid, localeCodes); + + ContentstackResponse response = _stack.Taxonomy(taxonomyUid).Unlocalize(localeCodes[0]); + AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Unlocalize failed: {response.OpenResponse()}", "UnlocalizeSuccess"); + AssertLogger.IsTrue(string.IsNullOrWhiteSpace(response.OpenResponse()), "Unlocalize response body is empty", "UnlocalizeEmptyBody"); + } + finally + { + DeleteTaxonomyPublishFixtures(taxonomies, new List(), locales); + } + } + + [TestMethod] + [DoNotParallelize] + public async Task Test285_Should_Unlocalize_Taxonomy_Async() + { + TestOutputLogger.LogContext("TestScenario", "Test285_Should_Unlocalize_Taxonomy_Async"); + var taxonomies = new List(); + var locales = new List(); + try + { + string taxonomyUid = CreatePublishFixtureTaxonomy(taxonomies); + var localeCodes = ResolveLocaleCodes(1, locales); + TestOutputLogger.LogContext("TaxonomyUid", taxonomyUid); + LocalizeFixtureToLocales(taxonomyUid, localeCodes); + + ContentstackResponse response = await _stack.Taxonomy(taxonomyUid).UnlocalizeAsync(localeCodes[0]); + AssertLogger.IsTrue(response.IsSuccessStatusCode, $"UnlocalizeAsync failed: {response.OpenResponse()}", "UnlocalizeAsyncSuccess"); + AssertLogger.IsTrue(string.IsNullOrWhiteSpace(response.OpenResponse()), "UnlocalizeAsync response body is empty", "UnlocalizeAsyncEmptyBody"); + } + finally + { + DeleteTaxonomyPublishFixtures(taxonomies, new List(), locales); + } + } + private static Stack GetStack() { StackResponse response = StackResponse.getStack(_client.serializer); diff --git a/Contentstack.Management.Core.Unit.Tests/Models/TaxonomyTest.cs b/Contentstack.Management.Core.Unit.Tests/Models/TaxonomyTest.cs index 66f7240..7fafd85 100644 --- a/Contentstack.Management.Core.Unit.Tests/Models/TaxonomyTest.cs +++ b/Contentstack.Management.Core.Unit.Tests/Models/TaxonomyTest.cs @@ -1,8 +1,16 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Net; +using System.Reflection; +using System.Threading.Tasks; using AutoFixture; using Contentstack.Management.Core.Models; +using Contentstack.Management.Core.Internal; using Contentstack.Management.Core.Queryable; +using Contentstack.Management.Core.Utils; +using Contentstack.Management.Core.Runtime.Contexts; +using Contentstack.Management.Core.Runtime.Pipeline; using Contentstack.Management.Core.Unit.Tests.Mokes; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text.Json; @@ -194,5 +202,775 @@ public void Localize_When_Api_Returns_400_Returns_Unsuccessful_Response() Assert.IsFalse(response.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } + + #region Taxonomy publish / unlocalize + + private const string PublishAck = "{\"notice\":\"Your publish request is accepted.\",\"job_id\":\"job_1\"}"; + + /// + /// Records the method, URI, headers and body of every outgoing request (the shared + /// MockHttpHandler keeps only the URI and headers) and answers with a canned response. + /// + private sealed class RecordingHandler : IPipelineHandler + { + private readonly ContentstackResponse _response; + + public RecordingHandler(ContentstackResponse response) + { + _response = response; + } + + public ILogManager LogManager { get; set; } + public IPipelineHandler InnerHandler { get; set; } + public int RequestCount { get; private set; } + public string Method { get; private set; } + public Uri Uri { get; private set; } + public IDictionary Headers { get; private set; } + public string Body { get; private set; } + public List> Query { get; private set; } + + public string Path + { + get { return Uri.AbsolutePath; } + } + + private void Record(IExecutionContext executionContext) + { + var service = (Contentstack.Management.Core.Services.ContentstackService)executionContext.RequestContext.service; + // The request the pipeline would really send: path and query come from its URI. + var httpRequest = service.CreateHttpRequest(null, executionContext.RequestContext.config); + RequestCount++; + Method = service.HttpMethod; + Uri = httpRequest.RequestUri; + Headers = new Dictionary(service.Headers, StringComparer.OrdinalIgnoreCase); + Body = service.ByteContent == null ? null : System.Text.Encoding.UTF8.GetString(service.ByteContent); + Query = ParseQuery(httpRequest.RequestUri.Query); + executionContext.ResponseContext.httpResponse = _response; + service.OnResponse(_response, executionContext.RequestContext.config); + } + + private static List> ParseQuery(string query) + { + var pairs = new List>(); + foreach (var part in query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)) + { + var kv = part.Split(new[] { '=' }, 2); + pairs.Add(new KeyValuePair(System.Net.WebUtility.UrlDecode(kv[0]), kv.Length > 1 ? System.Net.WebUtility.UrlDecode(kv[1]) : string.Empty)); + } + return pairs; + } + + public void InvokeSync(IExecutionContext executionContext, bool addAcceptMediaHeader = false, string apiVersion = null) + { + Record(executionContext); + } + + public Task InvokeAsync(IExecutionContext executionContext, bool addAcceptMediaHeader = false, string apiVersion = null) + { + Record(executionContext); + return Task.FromResult((T)executionContext.ResponseContext.httpResponse); + } + } + + private Stack NewStack(HttpStatusCode status, string body, out RecordingHandler handler, string branchUid = null) + { + var httpMsg = MockResponse.Create(status, null, body); + handler = new RecordingHandler(new ContentstackResponse(httpMsg, new JsonSerializerOptions())); + var client = new ContentstackClient(); + client.ContentstackPipeline.ReplaceHandler(handler); + client.contentstackOptions.Authtoken = _fixture.Create(); + return new Stack(client, _fixture.Create(), null, branchUid); + } + + private static TaxonomyPublishModel PublishModel(string uid = "tax_1", string locale = "en-us", string environment = "production") + { + return new TaxonomyPublishModel + { + Locales = new List { locale }, + Environments = new List { environment }, + Items = new List { new TaxonomyPublishItem { Uid = uid } } + }; + } + + private static string QueryValue(RecordingHandler handler, string key) + { + return handler.Query.Where(p => p.Key == key).Select(p => p.Value).SingleOrDefault(); + } + + [TestMethod] + public void Publish_Posts_Flat_Body_To_Taxonomies_Publish() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + + ContentstackResponse response = stack.Taxonomy().Publish(PublishModel()); + + Assert.AreEqual("POST", handler.Method); + Assert.IsTrue(handler.Path.EndsWith("/taxonomies/publish"), handler.Path); + using var doc = JsonDocument.Parse(handler.Body); + var root = doc.RootElement; + CollectionAssert.AreEquivalent(new[] { "locales", "environments", "items" }, root.EnumerateObject().Select(p => p.Name).ToArray()); + Assert.AreEqual("en-us", root.GetProperty("locales")[0].GetString()); + Assert.AreEqual("production", root.GetProperty("environments")[0].GetString()); + Assert.AreEqual("tax_1", root.GetProperty("items")[0].GetProperty("uid").GetString()); + Assert.IsTrue(response.IsSuccessStatusCode); + Assert.AreEqual(PublishAck, response.OpenResponse()); + } + + [TestMethod] + public async Task Publish_Posts_Flat_Body_To_Taxonomies_Publish_Async() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + + ContentstackResponse response = await stack.Taxonomy().PublishAsync(PublishModel()); + + Assert.AreEqual("POST", handler.Method); + Assert.IsTrue(handler.Path.EndsWith("/taxonomies/publish"), handler.Path); + using var doc = JsonDocument.Parse(handler.Body); + Assert.AreEqual("tax_1", doc.RootElement.GetProperty("items")[0].GetProperty("uid").GetString()); + Assert.IsFalse(doc.RootElement.TryGetProperty("taxonomy", out _)); + Assert.AreEqual(PublishAck, response.OpenResponse()); + } + + [TestMethod] + public void Publish_Multiple_Locales_And_Environments_Sends_One_Request() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = new TaxonomyPublishModel + { + Locales = new List { "en-us", "fr-fr", "de-de" }, + Environments = new List { "production", "staging" }, + Items = new List { new TaxonomyPublishItem { Uid = "tax_1" }, new TaxonomyPublishItem { Uid = "tax_2" } } + }; + + stack.Taxonomy().Publish(model); + + Assert.AreEqual(1, handler.RequestCount); + using var doc = JsonDocument.Parse(handler.Body); + var root = doc.RootElement; + CollectionAssert.AreEqual(new[] { "en-us", "fr-fr", "de-de" }, root.GetProperty("locales").EnumerateArray().Select(e => e.GetString()).ToArray()); + CollectionAssert.AreEqual(new[] { "production", "staging" }, root.GetProperty("environments").EnumerateArray().Select(e => e.GetString()).ToArray()); + CollectionAssert.AreEqual(new[] { "tax_1", "tax_2" }, root.GetProperty("items").EnumerateArray().Select(e => e.GetProperty("uid").GetString()).ToArray()); + } + + [TestMethod] + public void Publish_Sends_Branch_As_Header_Only() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = PublishModel(); + model.Branch = "feature_branch"; + + stack.Taxonomy().Publish(model); + + Assert.AreEqual("feature_branch", handler.Headers["branch"]); + Assert.IsFalse(handler.Body.Contains("branch")); + Assert.AreEqual(0, handler.Query.Count); + } + + [TestMethod] + public async Task Publish_Sends_Branch_As_Header_Only_Async() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = PublishModel(); + model.Branch = "feature_branch"; + + await stack.Taxonomy().PublishAsync(model); + + Assert.AreEqual("feature_branch", handler.Headers["branch"]); + Assert.IsFalse(handler.Body.Contains("branch")); + Assert.AreEqual(0, handler.Query.Count); + } + + // S3 with a stack that already has a branch: ContentstackService injects the stack's branch header + [TestMethod] + public void Publish_Model_Branch_Overrides_Stack_Branch_Header() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler, "stack_branch"); + var model = PublishModel(); + model.Branch = "model_branch"; + + stack.Taxonomy().Publish(model); + + Assert.AreEqual("model_branch", handler.Headers["branch"]); + Assert.AreEqual(1, handler.Headers.Keys.Count(k => string.Equals(k, "branch", StringComparison.OrdinalIgnoreCase))); + Assert.IsFalse(handler.Body.Contains("branch")); + } + + [TestMethod] + public void Publish_Keeps_Stack_Branch_Header_When_Model_Branch_Is_Null() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler, "stack_branch"); + + stack.Taxonomy().Publish(PublishModel()); + + Assert.AreEqual("stack_branch", handler.Headers["branch"]); + Assert.IsFalse(handler.Body.Contains("branch")); + } + + [TestMethod] + public void Publish_Surfaces_Taxonomy_Unauthorized_Untouched() + { + const string body = "{\"error_message\":\"Taxonomy publish is not authorized.\",\"error_code\":\"TAXONOMY_UNAUTHORIZED\"}"; + var stack = NewStack(HttpStatusCode.Forbidden, body, out _); + + ContentstackResponse response = stack.Taxonomy().Publish(PublishModel()); + + Assert.IsFalse(response.IsSuccessStatusCode); + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + Assert.AreEqual(body, response.OpenResponse()); + } + + [TestMethod] + public async Task Publish_Surfaces_Taxonomy_Unauthorized_Untouched_Async() + { + const string body = "{\"error_message\":\"Taxonomy publish is not authorized.\",\"error_code\":\"TAXONOMY_UNAUTHORIZED\"}"; + var stack = NewStack(HttpStatusCode.Forbidden, body, out _); + + ContentstackResponse response = await stack.Taxonomy().PublishAsync(PublishModel()); + + Assert.IsFalse(response.IsSuccessStatusCode); + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + Assert.AreEqual(body, response.OpenResponse()); + } + + [TestMethod] + public void Publish_Surfaces_Not_Localized_Untouched() + { + const string body = "{\"error_message\":\"Taxonomy is not localized in the requested locale.\",\"error_code\":\"NOT_LOCALIZED\"}"; + var stack = NewStack((HttpStatusCode)422, body, out _); + + ContentstackResponse response = stack.Taxonomy().Publish(PublishModel()); + + Assert.IsFalse(response.IsSuccessStatusCode); + Assert.AreEqual((HttpStatusCode)422, response.StatusCode); + Assert.AreEqual(body, response.OpenResponse()); + } + + [TestMethod] + public async Task Publish_Surfaces_Not_Localized_Untouched_Async() + { + const string body = "{\"error_message\":\"Taxonomy is not localized in the requested locale.\",\"error_code\":\"NOT_LOCALIZED\"}"; + var stack = NewStack((HttpStatusCode)422, body, out _); + + ContentstackResponse response = await stack.Taxonomy().PublishAsync(PublishModel()); + + Assert.IsFalse(response.IsSuccessStatusCode); + Assert.AreEqual((HttpStatusCode)422, response.StatusCode); + Assert.AreEqual(body, response.OpenResponse()); + } + + [TestMethod] + public void Unlocalize_Sends_Delete_With_Locale_Query_And_Does_Not_Parse_Empty_204() + { + var stack = NewStack(HttpStatusCode.NoContent, string.Empty, out var handler); + + ContentstackResponse response = stack.Taxonomy("tax_1").Unlocalize("fr-fr"); + + Assert.AreEqual("DELETE", handler.Method); + Assert.IsTrue(handler.Path.EndsWith("/taxonomies/tax_1"), handler.Path); + Assert.AreEqual("fr-fr", QueryValue(handler, "locale")); + Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); + Assert.IsTrue(response.IsSuccessStatusCode); + Assert.AreEqual(string.Empty, response.OpenResponse()); + } + + [TestMethod] + public async Task Unlocalize_Sends_Delete_With_Locale_Query_And_Does_Not_Parse_Empty_204_Async() + { + var stack = NewStack(HttpStatusCode.NoContent, string.Empty, out var handler); + + ContentstackResponse response = await stack.Taxonomy("tax_1").UnlocalizeAsync("fr-fr"); + + Assert.AreEqual("DELETE", handler.Method); + Assert.IsTrue(handler.Path.EndsWith("/taxonomies/tax_1"), handler.Path); + Assert.AreEqual("fr-fr", QueryValue(handler, "locale")); + Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); + Assert.AreEqual(string.Empty, response.OpenResponse()); + } + + // The locale is required and must be a plain code: a blank or unsafe one would put a different request + // on the wire (the locale is not URL-encoded), e.g. a whole-taxonomy DELETE. + [TestMethod] + [DataRow(null)] + [DataRow("")] + [DataRow(" ")] + [DataRow("#hi-in")] + [DataRow("#")] + [DataRow("&x")] + [DataRow("x&force=true")] + [DataRow(" fr-fr ")] + [DataRow("hi in")] + public void Unlocalize_Throws_When_Locale_Is_Blank(string locale) + { + var stack = NewStack(HttpStatusCode.NoContent, string.Empty, out var handler); + + var ex = Assert.ThrowsException(() => stack.Taxonomy("tax_1").Unlocalize(locale)); + + Assert.AreEqual("locale", ex.ParamName); + StringAssert.Contains(ex.Message, CSConstants.LocaleRequired); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + [DataRow(null)] + [DataRow("")] + [DataRow(" ")] + [DataRow("#hi-in")] + [DataRow("#")] + [DataRow("&x")] + [DataRow("x&force=true")] + [DataRow(" fr-fr ")] + [DataRow("hi in")] + public async Task Unlocalize_Throws_When_Locale_Is_Blank_Async(string locale) + { + var stack = NewStack(HttpStatusCode.NoContent, string.Empty, out var handler); + + var ex = await Assert.ThrowsExceptionAsync(() => stack.Taxonomy("tax_1").UnlocalizeAsync(locale)); + + Assert.AreEqual("locale", ex.ParamName); + StringAssert.Contains(ex.Message, CSConstants.LocaleRequired); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + [DataRow("hi-in")] + [DataRow("en-us")] + [DataRow("pt_BR")] + [DataRow("zh-Hans")] + public void Unlocalize_Sends_Valid_Locale_Codes(string locale) + { + var stack = NewStack(HttpStatusCode.NoContent, string.Empty, out var handler); + + stack.Taxonomy("tax_1").Unlocalize(locale); + + Assert.AreEqual(1, handler.RequestCount); + Assert.AreEqual("DELETE", handler.Method); + Assert.AreEqual(locale, QueryValue(handler, "locale")); + } + + // Guard order matches the other methods: login first, then uid, then the arguments. + [TestMethod] + public void Unlocalize_Checks_Login_Before_Locale() + { + // Stack.Taxonomy() itself needs a login, so log out after building the model. + var taxonomy = _stack.Taxonomy("tax_1"); + _stack.client.contentstackOptions.Authtoken = null; + + var ex = Assert.ThrowsException(() => taxonomy.Unlocalize(null)); + + Assert.AreEqual(CSConstants.YouAreNotLoggedIn, ex.Message); + } + + [TestMethod] + public async Task Unlocalize_Checks_Login_Before_Locale_Async() + { + var taxonomy = _stack.Taxonomy("tax_1"); + _stack.client.contentstackOptions.Authtoken = null; + + var ex = await Assert.ThrowsExceptionAsync(() => taxonomy.UnlocalizeAsync(null)); + + Assert.AreEqual(CSConstants.YouAreNotLoggedIn, ex.Message); + } + + [TestMethod] + public void Unlocalize_Checks_Uid_Before_Locale() + { + var ex = Assert.ThrowsException(() => _stack.Taxonomy().Unlocalize(null)); + + Assert.AreEqual("uid", ex.ParamName); + } + + [TestMethod] + public async Task Unlocalize_Checks_Uid_Before_Locale_Async() + { + var ex = await Assert.ThrowsExceptionAsync(() => _stack.Taxonomy().UnlocalizeAsync(null)); + + Assert.AreEqual("uid", ex.ParamName); + } + + [TestMethod] + public void Publish_Items_Carry_Uid_Only_Never_Term_Uid() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + + stack.Taxonomy().Publish(PublishModel()); + + using var doc = JsonDocument.Parse(handler.Body); + foreach (var item in doc.RootElement.GetProperty("items").EnumerateArray()) + { + CollectionAssert.AreEqual(new[] { "uid" }, item.EnumerateObject().Select(p => p.Name).ToArray()); + } + Assert.IsFalse(handler.Body.Contains("term_uid")); + } + + // A null element in Items must not become a NullReferenceException; it is sent as {"uid":null} and the API rejects it. + [TestMethod] + public void Publish_With_Null_Item_Sends_Null_Uid_And_Does_Not_Throw() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = PublishModel(); + model.Items = new List { null }; + + stack.Taxonomy().Publish(model); + + Assert.AreEqual(1, handler.RequestCount); + using var doc = JsonDocument.Parse(handler.Body); + var item = doc.RootElement.GetProperty("items")[0]; + Assert.AreEqual(JsonValueKind.Null, item.GetProperty("uid").ValueKind); + } + + // Guard order for Publish: login, then collection-level, then Branch, then the service's null-model check. + // A uid-bound taxonomy with a bad Branch, logged out, trips every guard, so only the first one can be the answer. + private static TaxonomyPublishModel PublishModelWithBadBranch() + { + var model = PublishModel(); + model.Branch = "a\nb"; + return model; + } + + [TestMethod] + public void Publish_Checks_Login_Before_Other_Guards() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var taxonomy = stack.Taxonomy("tax_1"); + stack.client.contentstackOptions.Authtoken = null; + + var ex = Assert.ThrowsException(() => taxonomy.Publish(PublishModelWithBadBranch())); + + Assert.AreEqual(CSConstants.YouAreNotLoggedIn, ex.Message); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + public async Task Publish_Checks_Login_Before_Other_Guards_Async() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var taxonomy = stack.Taxonomy("tax_1"); + stack.client.contentstackOptions.Authtoken = null; + + var ex = await Assert.ThrowsExceptionAsync(() => taxonomy.PublishAsync(PublishModelWithBadBranch())); + + Assert.AreEqual(CSConstants.YouAreNotLoggedIn, ex.Message); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + public void Publish_Checks_Collection_Level_Before_Branch() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + + var ex = Assert.ThrowsException(() => stack.Taxonomy("tax_1").Publish(PublishModelWithBadBranch())); + + Assert.AreEqual(CSConstants.OperationNotAllowedOnModel, ex.Message); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + public async Task Publish_Checks_Collection_Level_Before_Branch_Async() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + + var ex = await Assert.ThrowsExceptionAsync(() => stack.Taxonomy("tax_1").PublishAsync(PublishModelWithBadBranch())); + + Assert.AreEqual(CSConstants.OperationNotAllowedOnModel, ex.Message); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + public void Publish_Throws_When_Model_Is_Null() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + + var ex = Assert.ThrowsException(() => stack.Taxonomy().Publish(null)); + + Assert.AreEqual("model", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.PublishDetailsRequired); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + public async Task Publish_Throws_When_Model_Is_Null_Async() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + + var ex = await Assert.ThrowsExceptionAsync(() => stack.Taxonomy().PublishAsync(null)); + + Assert.AreEqual("model", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.PublishDetailsRequired); + Assert.AreEqual(0, handler.RequestCount); + } + + // S10 (publish is collection-level only) + [TestMethod] + public void Publish_Throws_When_Taxonomy_Is_Uid_Bound() + { + var ex = Assert.ThrowsException(() => _stack.Taxonomy(_fixture.Create()).Publish(PublishModel())); + + Assert.AreEqual(CSConstants.OperationNotAllowedOnModel, ex.Message); + } + + [TestMethod] + public async Task Publish_Throws_When_Taxonomy_Is_Uid_Bound_Async() + { + var ex = await Assert.ThrowsExceptionAsync(() => _stack.Taxonomy(_fixture.Create()).PublishAsync(PublishModel())); + + Assert.AreEqual(CSConstants.OperationNotAllowedOnModel, ex.Message); + } + + // S12 (unlocalize is instance-level only) + [TestMethod] + public void Unlocalize_Throws_When_Uid_Is_Missing() + { + var ex = Assert.ThrowsException(() => _stack.Taxonomy().Unlocalize("fr-fr")); + + Assert.AreEqual("uid", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.MissingUID); + } + + [TestMethod] + public async Task Unlocalize_Throws_When_Uid_Is_Missing_Async() + { + var ex = await Assert.ThrowsExceptionAsync(() => _stack.Taxonomy().UnlocalizeAsync("fr-fr")); + + Assert.AreEqual("uid", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.MissingUID); + } + + // S13 (empty-string uid is rejected exactly like a missing uid) + [TestMethod] + public void Unlocalize_Throws_When_Uid_Is_Empty_String() + { + var ex = Assert.ThrowsException(() => _stack.Taxonomy("").Unlocalize("fr-fr")); + + Assert.AreEqual("uid", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.MissingUID); + } + + [TestMethod] + public async Task Unlocalize_Throws_When_Uid_Is_Empty_String_Async() + { + var ex = await Assert.ThrowsExceptionAsync(() => _stack.Taxonomy("").UnlocalizeAsync("fr-fr")); + + Assert.AreEqual("uid", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.MissingUID); + } + + // Pins the existing, already-shipped behaviour of the protected Localize (ThrowIfUidEmpty). + // It compiles green once the types exist; that is intended for this one regression pin. + [TestMethod] + public void Localize_Throws_When_Uid_Is_Empty_String() + { + Assert.ThrowsException(() => _stack.Taxonomy("").Localize(_fixture.Create())); + } + + [TestMethod] + public async Task Localize_Throws_When_Uid_Is_Empty_String_Async() + { + await Assert.ThrowsExceptionAsync(() => _stack.Taxonomy("").LocalizeAsync(_fixture.Create())); + } + + [TestMethod] + public void Publish_Throws_When_Taxonomy_Uid_Is_Empty_String() + { + var ex = Assert.ThrowsException(() => _stack.Taxonomy("").Publish(PublishModel())); + + Assert.AreEqual(CSConstants.OperationNotAllowedOnModel, ex.Message); + } + + [TestMethod] + public async Task Publish_Throws_When_Taxonomy_Uid_Is_Empty_String_Async() + { + var ex = await Assert.ThrowsExceptionAsync(() => _stack.Taxonomy("").PublishAsync(PublishModel())); + + Assert.AreEqual(CSConstants.OperationNotAllowedOnModel, ex.Message); + } + + // S14 (no client-side validation: empty lists are sent as given) + [TestMethod] + public void Publish_With_Empty_Lists_Sends_Them_As_Given() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = new TaxonomyPublishModel + { + Locales = new List(), + Environments = new List(), + Items = new List() + }; + + stack.Taxonomy().Publish(model); + + Assert.AreEqual(1, handler.RequestCount); + using var doc = JsonDocument.Parse(handler.Body); + foreach (var name in new[] { "locales", "environments", "items" }) + { + Assert.AreEqual(JsonValueKind.Array, doc.RootElement.GetProperty(name).ValueKind); + Assert.AreEqual(0, doc.RootElement.GetProperty(name).GetArrayLength()); + } + } + + // S15 (the locale argument wins over a locale already in the caller's collection) + [TestMethod] + public void Unlocalize_Locale_Argument_Wins_Over_Collection_Locale() + { + var stack = NewStack(HttpStatusCode.NoContent, string.Empty, out var handler); + var collection = new ParameterCollection(); + collection.Add("locale", "en-us"); + collection.Add("x_param", "x"); + + stack.Taxonomy("tax_1").Unlocalize("fr-fr", collection); + + Assert.AreEqual(1, handler.Query.Count(p => p.Key == "locale")); + Assert.AreEqual("fr-fr", QueryValue(handler, "locale")); + Assert.AreEqual("x", QueryValue(handler, "x_param")); + } + + [TestMethod] + public async Task Unlocalize_Locale_Argument_Wins_Over_Collection_Locale_Async() + { + var stack = NewStack(HttpStatusCode.NoContent, string.Empty, out var handler); + var collection = new ParameterCollection(); + collection.Add("locale", "en-us"); + + await stack.Taxonomy("tax_1").UnlocalizeAsync("fr-fr", collection); + + Assert.AreEqual(1, handler.Query.Count(p => p.Key == "locale")); + Assert.AreEqual("fr-fr", QueryValue(handler, "locale")); + } + + // A whitespace-only model Branch is ignored, so the stack branch header stays. + [TestMethod] + public void Publish_Keeps_Stack_Branch_Header_When_Model_Branch_Is_Whitespace() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler, "stack_branch"); + var model = PublishModel(); + model.Branch = " "; + + stack.Taxonomy().Publish(model); + + Assert.AreEqual("stack_branch", handler.Headers["branch"]); + Assert.IsFalse(handler.Body.Contains("branch")); + } + + // A Branch with a control character would inject a header line, so it is rejected before any request. + [TestMethod] + [DataRow("main\r\nX-Evil: 1")] + [DataRow("a\nb")] + [DataRow("a\tb")] + [DataRow("a\0b")] + [DataRow("a\rb")] + [DataRow("a\u007fb")] + [DataRow("a\u0085b")] + public void Publish_Throws_When_Branch_Contains_Control_Character(string branch) + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = PublishModel(); + model.Branch = branch; + + var ex = Assert.ThrowsException(() => stack.Taxonomy().Publish(model)); + + Assert.AreEqual("Branch", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.BranchInvalid); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + [DataRow("main\r\nX-Evil: 1")] + [DataRow("a\nb")] + [DataRow("a\tb")] + [DataRow("a\0b")] + [DataRow("a\rb")] + [DataRow("a\u007fb")] + [DataRow("a\u0085b")] + public async Task Publish_Throws_When_Branch_Contains_Control_Character_Async(string branch) + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = PublishModel(); + model.Branch = branch; + + var ex = await Assert.ThrowsExceptionAsync(() => stack.Taxonomy().PublishAsync(model)); + + Assert.AreEqual("Branch", ex.ParamName); + StringAssert.StartsWith(ex.Message, CSConstants.BranchInvalid); + Assert.AreEqual(0, handler.RequestCount); + } + + [TestMethod] + [DataRow("main")] + [DataRow("feature-1")] + [DataRow("dev_2")] + public void Publish_Sends_Valid_Branch_Unchanged(string branch) + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = PublishModel(); + model.Branch = branch; + + stack.Taxonomy().Publish(model); + + Assert.AreEqual(1, handler.RequestCount); + Assert.AreEqual(branch, handler.Headers["branch"]); + } + + [TestMethod] + [DataRow("main")] + [DataRow("feature-1")] + [DataRow("dev_2")] + public async Task Publish_Sends_Valid_Branch_Unchanged_Async(string branch) + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var model = PublishModel(); + model.Branch = branch; + + await stack.Taxonomy().PublishAsync(model); + + Assert.AreEqual(1, handler.RequestCount); + Assert.AreEqual(branch, handler.Headers["branch"]); + } + + // S16 (isolation) + [TestMethod] + public void Publish_Branch_Header_And_Params_Do_Not_Leak_Into_The_Next_Call() + { + var stack = NewStack(HttpStatusCode.OK, PublishAck, out var handler); + var first = PublishModel("tax_1"); + first.Branch = "feature_branch"; + var collection = new ParameterCollection(); + collection.Add("x_param", "x"); + + stack.Taxonomy().Publish(first, collection); + Assert.AreEqual("feature_branch", handler.Headers["branch"]); + Assert.AreEqual("x", QueryValue(handler, "x_param")); + + stack.Taxonomy().Publish(PublishModel("tax_2")); + + Assert.AreEqual(2, handler.RequestCount); + Assert.IsFalse(handler.Headers.ContainsKey("branch")); + Assert.AreEqual(0, handler.Query.Count); + using var doc = JsonDocument.Parse(handler.Body); + Assert.AreEqual("tax_2", doc.RootElement.GetProperty("items")[0].GetProperty("uid").GetString()); + Assert.AreEqual(1, doc.RootElement.GetProperty("items").GetArrayLength()); + } + + // S17, S18 (absence: no api_version, no scheduled_at) + [TestMethod] + public void TaxonomyPublishModel_Exposes_Only_Locales_Environments_Items_And_Branch() + { + var names = typeof(TaxonomyPublishModel).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => p.Name).ToArray(); + + CollectionAssert.AreEquivalent(new[] { "Locales", "Environments", "Items", "Branch" }, names); + Assert.AreEqual(0, typeof(TaxonomyPublishModel).GetFields(BindingFlags.Public | BindingFlags.Instance).Length); + CollectionAssert.AreEquivalent(new[] { "Uid" }, typeof(TaxonomyPublishItem).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => p.Name).ToArray()); + } + + [TestMethod] + public void Publish_Methods_Accept_No_Api_Version_Or_Scheduled_At_Parameter() + { + foreach (var name in new[] { "Publish", "PublishAsync" }) + { + MethodInfo method = typeof(Taxonomy).GetMethod(name); + Assert.IsNotNull(method, name); + CollectionAssert.AreEqual(new[] { "model", "collection" }, method.GetParameters().Select(p => p.Name).ToArray()); + } + } + + #endregion } } diff --git a/Contentstack.Management.Core/Models/Taxonomy.cs b/Contentstack.Management.Core/Models/Taxonomy.cs index 3614312..9989f9c 100644 --- a/Contentstack.Management.Core/Models/Taxonomy.cs +++ b/Contentstack.Management.Core/Models/Taxonomy.cs @@ -1,7 +1,9 @@ using System; +using System.Linq; using System.Threading.Tasks; using Contentstack.Management.Core.Queryable; using Contentstack.Management.Core.Services.Models; +using Contentstack.Management.Core.Utils; namespace Contentstack.Management.Core.Models { @@ -10,10 +12,12 @@ namespace Contentstack.Management.Core.Models /// public class Taxonomy : BaseModel { + private const string CollectionPath = "/taxonomies"; + internal Taxonomy(Stack stack, string? uid = null) : base(stack, "taxonomy", uid) { - resourcePath = uid == null ? "/taxonomies" : $"/taxonomies/{uid}"; + resourcePath = uid == null ? CollectionPath : $"{CollectionPath}/{uid}"; } /// @@ -160,6 +164,128 @@ public Task LocalizeAsync(TaxonomyModel model, ParameterCo return stack.client.InvokeAsync, ContentstackResponse>(service); } + /// + /// Publish taxonomies to the given environments and locales. POST /taxonomies/publish with a flat body + /// { locales, environments, items: [{ uid }] }. Branch, when set on the model, is sent as the branch header. + /// A 2xx response means the publish request was ACCEPTED for processing, not that publishing has completed. + /// Monitor the publish queue and the publish-failure webhooks to learn the outcome. + /// Must be called on the collection-level instance (stack.Taxonomy()); throws InvalidOperationException on a uid-bound instance. + /// + /// + /// + /// var model = new TaxonomyPublishModel + /// { + /// Locales = new List<string> { "en-us" }, + /// Environments = new List<string> { "production" }, + /// Items = new List<TaxonomyPublishItem> { new TaxonomyPublishItem { Uid = "taxonomy_uid" } } + /// }; + /// ContentstackResponse response = stack.Taxonomy().Publish(model); + /// + /// + /// Locales, environments and taxonomy items to publish; an optional Branch is sent as the branch header. + /// Optional additional query parameters. + public ContentstackResponse Publish(TaxonomyPublishModel model, ParameterCollection? collection = null) + { + stack.ThrowIfNotLoggedIn(); + ThrowIfNotCollectionLevel(); + ThrowIfBranchInvalid(model); + var service = new TaxonomyPublishUnpublishService(stack, model, $"{resourcePath}/publish", collection); + return stack.client.InvokeSync(service); + } + + /// + /// Publish taxonomies asynchronously. A 2xx response means the publish request was ACCEPTED, not that publishing has completed; + /// monitor the publish queue and the publish-failure webhooks to learn the outcome. + /// Must be called on the collection-level instance (stack.Taxonomy()); throws InvalidOperationException on a uid-bound instance. + /// + /// Locales, environments and taxonomy items to publish; an optional Branch is sent as the branch header. + /// Optional additional query parameters. + public Task PublishAsync(TaxonomyPublishModel model, ParameterCollection? collection = null) + { + stack.ThrowIfNotLoggedIn(); + ThrowIfNotCollectionLevel(); + ThrowIfBranchInvalid(model); + var service = new TaxonomyPublishUnpublishService(stack, model, $"{resourcePath}/publish", collection); + return stack.client.InvokeAsync(service); + } + + /// + /// Unlocalize taxonomy. DELETE {resourcePath} with the given locale as the locale query parameter. + /// The API answers 204 No Content with an empty body, which is not parsed. + /// + /// + /// + /// ContentstackResponse response = stack.Taxonomy("taxonomy_uid").Unlocalize("hi-in"); + /// + /// + /// Code of the locale to unlocalize the taxonomy from. Required: letters, digits, '-' or '_' only. Wins over a locale already in the collection. + /// Optional additional query parameters. + public ContentstackResponse Unlocalize(string locale, ParameterCollection? collection = null) + { + // base.Delete repeats these two checks; they are explicit so the locale is checked after login and uid. + stack.ThrowIfNotLoggedIn(); + ThrowIfUidEmpty(); + ThrowIfLocaleInvalid(locale); + return base.Delete(WithLocale(locale, collection)); + } + + /// + /// Unlocalize taxonomy asynchronously. DELETE {resourcePath} with the given locale as the locale query parameter. + /// The API answers 204 No Content with an empty body, which is not parsed. + /// + /// Code of the locale to unlocalize the taxonomy from. Required: letters, digits, '-' or '_' only. Wins over a locale already in the collection. + /// Optional additional query parameters. + public Task UnlocalizeAsync(string locale, ParameterCollection? collection = null) + { + // base.DeleteAsync repeats these two checks; they are explicit so the locale is checked after login and uid. + stack.ThrowIfNotLoggedIn(); + ThrowIfUidEmpty(); + ThrowIfLocaleInvalid(locale); + return base.DeleteAsync(WithLocale(locale, collection)); + } + + private static ParameterCollection WithLocale(string locale, ParameterCollection? collection) + { + var result = new ParameterCollection(); + if (collection != null) + { + foreach (var pair in collection) + { + result[pair.Key] = pair.Value; + } + } + result["locale"] = new StringParameterValue(locale); + return result; + } + + // The locale goes on the query string unencoded, so anything but a plain code could change the request. + private static void ThrowIfLocaleInvalid(string locale) + { + if (string.IsNullOrEmpty(locale) || !locale.All(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_')) + { + throw new ArgumentException(CSConstants.LocaleRequired, "locale"); + } + } + + // The branch value becomes a request header; a control character (CR, LF, TAB, ...) would inject another header line. + private static void ThrowIfBranchInvalid(TaxonomyPublishModel model) + { + if (model?.Branch != null && model.Branch.Any(char.IsControl)) + { + throw new ArgumentException(CSConstants.BranchInvalid, "Branch"); + } + } + + // Stricter than BaseModel.ThrowIfUidNotEmpty on purpose: it also rejects Taxonomy(""), because + // with the base guard Taxonomy("").Publish would POST to /taxonomies//publish. + private void ThrowIfNotCollectionLevel() + { + if (resourcePath != CollectionPath) + { + throw new InvalidOperationException(CSConstants.OperationNotAllowedOnModel); + } + } + /// /// Import taxonomy. POST /taxonomies/import with multipart form (taxonomy file). /// diff --git a/Contentstack.Management.Core/Models/TaxonomyPublishModel.cs b/Contentstack.Management.Core/Models/TaxonomyPublishModel.cs new file mode 100644 index 0000000..7be204f --- /dev/null +++ b/Contentstack.Management.Core/Models/TaxonomyPublishModel.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; + +namespace Contentstack.Management.Core.Models +{ + /// + /// Model for publishing taxonomies to one or more environments and locales. + /// + public class TaxonomyPublishModel + { + /// + /// Locale codes to publish to. + /// + public List Locales { get; set; } = new List(); + + /// + /// Environment names to publish to. + /// + public List Environments { get; set; } = new List(); + + /// + /// Taxonomies to publish, each identified by its uid. + /// + public List Items { get; set; } = new List(); + + /// + /// Optional branch to publish from. Sent as the branch header, never in the body. + /// + public string? Branch { get; set; } + } + + /// + /// A taxonomy to publish. + /// + public class TaxonomyPublishItem + { + /// + /// Uid of the taxonomy to publish. + /// + public string? Uid { get; set; } + } +} diff --git a/Contentstack.Management.Core/Services/Models/TaxonomyPublishUnpublishService.cs b/Contentstack.Management.Core/Services/Models/TaxonomyPublishUnpublishService.cs new file mode 100644 index 0000000..f9daca4 --- /dev/null +++ b/Contentstack.Management.Core/Services/Models/TaxonomyPublishUnpublishService.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Contentstack.Management.Core.Models; +using Contentstack.Management.Core.Queryable; +using Contentstack.Management.Core.Utils; + +namespace Contentstack.Management.Core.Services.Models +{ + internal class TaxonomyPublishUnpublishService : ContentstackService + { + internal TaxonomyPublishModel model; + + internal TaxonomyPublishUnpublishService(Core.Models.Stack stack, TaxonomyPublishModel model, string resourcePath, ParameterCollection? collection = null, JsonSerializerOptions? stjOptions = null) + : base(stjOptions ?? stack?.client?.SerializerOptions ?? new JsonSerializerOptions(), stack: stack, collection: collection) + { + if (stack!.APIKey == null) + { + throw new ArgumentNullException("stack", CSConstants.MissingAPIKey); + } + + if (model == null) + { + throw new ArgumentNullException("model", CSConstants.PublishDetailsRequired); + } + + if (resourcePath == null) + { + throw new ArgumentNullException("resourcePath", CSConstants.ResourcePathRequired); + } + + this.ResourcePath = resourcePath; + this.HttpMethod = "POST"; + this.model = model; + + if (!string.IsNullOrWhiteSpace(model.Branch)) + { + this.Headers["branch"] = model.Branch!; + } + + if (collection != null && collection.Count > 0) + { + this.UseQueryString = true; + } + } + + public override void ContentBody() + { + using var stream = new MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + writer.WriteStartObject(); + + writer.WritePropertyName("locales"); + writer.WriteStartArray(); + foreach (string locale in model.Locales ?? new List()) + writer.WriteStringValue(locale); + writer.WriteEndArray(); + + writer.WritePropertyName("environments"); + writer.WriteStartArray(); + foreach (string environment in model.Environments ?? new List()) + writer.WriteStringValue(environment); + writer.WriteEndArray(); + + writer.WritePropertyName("items"); + writer.WriteStartArray(); + foreach (var item in model.Items ?? new List()) + { + writer.WriteStartObject(); + writer.WriteString("uid", item?.Uid); + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + writer.WriteEndObject(); + writer.Flush(); + + ByteContent = stream.ToArray(); + } + } +} diff --git a/Contentstack.Management.Core/Utils/CSConstants.cs b/Contentstack.Management.Core/Utils/CSConstants.cs index d967b74..798daec 100644 --- a/Contentstack.Management.Core/Utils/CSConstants.cs +++ b/Contentstack.Management.Core/Utils/CSConstants.cs @@ -84,6 +84,8 @@ public static class CSConstants internal const string InvitationsRequired = "Invitations are required. Provide valid Invitations and try again."; internal const string EmailRequired = "Email is required. Provide a valid Email and try again."; internal const string StackNameInvalid = "Stack Name is invalid. Provide a valid Stack Name and try again."; + internal const string LocaleRequired = "A valid Locale code is required. Use letters, digits, '-' or '_' and try again."; + internal const string BranchInvalid = "Branch contains invalid characters. Provide a valid Branch and try again."; internal const string LocaleInvalid = "Locale is invalid for this Stack. Provide a valid Locale and try again."; internal const string OrganizationUIDInvalid = "Organization UID is invalid. Provide a valid Organization UID and try again."; internal const string MasterLocaleRequired = "Master Locale is required when creating the Stack. Provide a valid Master Locale and try again."; diff --git a/Directory.Build.props b/Directory.Build.props index 8bdd5df..d602e14 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,5 @@ - 1.2.0 + 1.3.0