Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve document schedule #17535

Open
wants to merge 17 commits into
base: v15/dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Api.Management.Factories;
using Umbraco.Cms.Api.Management.Security.Authorization.Content;
using Umbraco.Cms.Api.Management.ViewModels.Document;
using Umbraco.Cms.Core.Actions;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Security.Authorization;
using Umbraco.Cms.Core.Services;
Expand All @@ -20,7 +22,9 @@ public class ByKeyDocumentController : DocumentControllerBase
private readonly IAuthorizationService _authorizationService;
private readonly IContentEditingService _contentEditingService;
private readonly IDocumentPresentationFactory _documentPresentationFactory;
private readonly IContentService _contentService;

[Obsolete("Scheduled for removal in v17")]
public ByKeyDocumentController(
IAuthorizationService authorizationService,
IContentEditingService contentEditingService,
Expand All @@ -29,6 +33,20 @@ public ByKeyDocumentController(
_authorizationService = authorizationService;
_contentEditingService = contentEditingService;
_documentPresentationFactory = documentPresentationFactory;
_contentService = StaticServiceProvider.Instance.GetRequiredService<IContentService>();
}

[ActivatorUtilitiesConstructor]
public ByKeyDocumentController(
IAuthorizationService authorizationService,
IContentEditingService contentEditingService,
IDocumentPresentationFactory documentPresentationFactory,
IContentService contentService)
{
_authorizationService = authorizationService;
_contentEditingService = contentEditingService;
_documentPresentationFactory = documentPresentationFactory;
_contentService = contentService;
}

[HttpGet("{id:guid}")]
Expand All @@ -53,7 +71,9 @@ public async Task<IActionResult> ByKey(CancellationToken cancellationToken, Guid
return DocumentNotFound();
}

DocumentResponseModel model = await _documentPresentationFactory.CreateResponseModelAsync(content);
ContentScheduleCollection schedule = _contentService.GetContentScheduleByContentId(content.Id);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not optimal to call two services from the controller. I think we should make it a single service call and move the logic to the service layer. Furthermore, when using two services, we should wrap it in a single scope, to avoid funny things that can happen outside of a transaction


DocumentResponseModel model = await _documentPresentationFactory.CreateResponseModelAsync(content, schedule);
return Ok(model);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ public async Task<IActionResult> Publish(CancellationToken cancellationToken, Gu
{
AuthorizationResult authorizationResult = await _authorizationService.AuthorizeResourceAsync(
User,
ContentPermissionResource.WithKeys(ActionPublish.ActionLetter, id, requestModel.PublishSchedules.Where(x=>x.Culture is not null).Select(x=>x.Culture!)),
ContentPermissionResource.WithKeys(ActionPublish.ActionLetter, id, requestModel.PublishSchedules.Where(x => x.Culture is not null).Select(x=>x.Culture!)),
AuthorizationPolicies.ContentPermissionByResource);

if (!authorizationResult.Succeeded)
{
return Forbidden();
}

Attempt<CultureAndScheduleModel, ContentPublishingOperationStatus> modelResult = _documentPresentationFactory.CreateCultureAndScheduleModel(requestModel);
Attempt<List<CulturePublishScheduleModel>, ContentPublishingOperationStatus> modelResult = _documentPresentationFactory.CreateCulturePublishScheduleModels(requestModel);

if (modelResult.Success is false)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Umbraco.Cms.Api.Management.Mapping.Content;

Check notice on line 1 in src/Umbraco.Cms.Api.Management/Factories/DocumentPresentationFactory.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (v15/dev)

ℹ Getting worse: Code Duplication

introduced similar code in: CreateResponseModelAsync. Avoid duplicated, aka copy-pasted, code inside the module. More duplication lowers the code health.

Check warning on line 1 in src/Umbraco.Cms.Api.Management/Factories/DocumentPresentationFactory.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (v15/dev)

❌ New issue: Overall Code Complexity

This module has a mean cyclomatic complexity of 4.20 across 10 functions. The mean complexity threshold is 4. This file has many conditional statements (e.g. if, for, while) across its implementation, leading to lower code health. Avoid adding more conditionals.
using Umbraco.Cms.Api.Management.ViewModels;
using Umbraco.Cms.Api.Management.ViewModels.Document;
using Umbraco.Cms.Api.Management.ViewModels.Document.Item;
Expand Down Expand Up @@ -37,6 +37,7 @@
_timeProvider = timeProvider;
}

[Obsolete("Schedule for removal in v17")]
public async Task<DocumentResponseModel> CreateResponseModelAsync(IContent content)
{
DocumentResponseModel responseModel = _umbracoMapper.Map<DocumentResponseModel>(content)!;
Expand Down Expand Up @@ -71,6 +72,24 @@
return responseModel;
}

public async Task<DocumentResponseModel> CreateResponseModelAsync(IContent content, ContentScheduleCollection schedule)
{
DocumentResponseModel responseModel = _umbracoMapper.Map<DocumentResponseModel>(content)!;
_umbracoMapper.Map(schedule, responseModel);

responseModel.Urls = await _documentUrlFactory.CreateUrlsAsync(content);

Guid? templateKey = content.TemplateId.HasValue
? _templateService.GetAsync(content.TemplateId.Value).Result?.Key
: null;

responseModel.Template = templateKey.HasValue
? new ReferenceByIdModel { Id = templateKey.Value }
: null;

return responseModel;
}

public DocumentItemResponseModel CreateItemResponseModel(IDocumentEntitySlim entity)
{
var responseModel = new DocumentItemResponseModel
Expand Down Expand Up @@ -128,6 +147,7 @@
public DocumentTypeReferenceResponseModel CreateDocumentTypeReferenceResponseModel(IDocumentEntitySlim entity)
=> _umbracoMapper.Map<DocumentTypeReferenceResponseModel>(entity)!;

[Obsolete("Use CreateCulturePublishScheduleModels instead. Scheduled for removal in v17")]
public Attempt<CultureAndScheduleModel, ContentPublishingOperationStatus> CreateCultureAndScheduleModel(PublishDocumentRequestModel requestModel)
{
var contentScheduleCollection = new ContentScheduleCollection();
Expand All @@ -136,7 +156,7 @@
{
if (cultureAndScheduleRequestModel.Schedule is null || (cultureAndScheduleRequestModel.Schedule.PublishTime is null && cultureAndScheduleRequestModel.Schedule.UnpublishTime is null))
{
culturesToPublishImmediately.Add(cultureAndScheduleRequestModel.Culture ?? "*"); // API have `null` for invariant, but service layer has "*".
culturesToPublishImmediately.Add(cultureAndScheduleRequestModel.Culture ?? Constants.System.InvariantCulture); // API have `null` for invariant, but service layer has "*".
continue;
}

Expand All @@ -152,7 +172,7 @@
}

contentScheduleCollection.Add(new ContentSchedule(
cultureAndScheduleRequestModel.Culture ?? "*",
cultureAndScheduleRequestModel.Culture ?? Constants.System.InvariantCulture,
cultureAndScheduleRequestModel.Schedule.PublishTime.Value.UtcDateTime,
ContentScheduleAction.Release));
}
Expand All @@ -177,7 +197,7 @@
}

contentScheduleCollection.Add(new ContentSchedule(
cultureAndScheduleRequestModel.Culture ?? "*",
cultureAndScheduleRequestModel.Culture ?? Constants.System.InvariantCulture,
cultureAndScheduleRequestModel.Schedule.UnpublishTime.Value.UtcDateTime,
ContentScheduleAction.Expire));
}
Expand All @@ -188,4 +208,53 @@
CulturesToPublishImmediately = culturesToPublishImmediately,
});
}

// NOTE: Keep the default implementation on the interface in line with this one until
// the default implementation can be removed
public Attempt<List<CulturePublishScheduleModel>, ContentPublishingOperationStatus> CreateCulturePublishScheduleModels(PublishDocumentRequestModel requestModel)
{
var model = new List<CulturePublishScheduleModel>();

foreach (CultureAndScheduleRequestModel cultureAndScheduleRequestModel in requestModel.PublishSchedules)
{
if (cultureAndScheduleRequestModel.Schedule is null)
{
model.Add(new CulturePublishScheduleModel
{
Culture = cultureAndScheduleRequestModel.Culture
?? Constants.System.InvariantCulture // API have `null` for invariant, but service layer has "*".
});
continue;
}

if (cultureAndScheduleRequestModel.Schedule.PublishTime is not null
&& cultureAndScheduleRequestModel.Schedule.PublishTime <= _timeProvider.GetUtcNow())
{
return Attempt.FailWithStatus(ContentPublishingOperationStatus.PublishTimeNeedsToBeInFuture, model);
}

if (cultureAndScheduleRequestModel.Schedule.UnpublishTime is not null
&& cultureAndScheduleRequestModel.Schedule.UnpublishTime <= _timeProvider.GetUtcNow())
{
return Attempt.FailWithStatus(ContentPublishingOperationStatus.UpublishTimeNeedsToBeInFuture, model);
}

if (cultureAndScheduleRequestModel.Schedule.UnpublishTime <= cultureAndScheduleRequestModel.Schedule.PublishTime)
{
return Attempt.FailWithStatus(ContentPublishingOperationStatus.UnpublishTimeNeedsToBeAfterPublishTime, model);
}

model.Add(new CulturePublishScheduleModel
{
Culture = cultureAndScheduleRequestModel.Culture,
Schedule = new ContentScheduleModel
{
PublishDate = cultureAndScheduleRequestModel.Schedule.PublishTime,
UnpublishDate = cultureAndScheduleRequestModel.Schedule.UnpublishTime,
},
});
}

return Attempt.SucceedWithStatus(ContentPublishingOperationStatus.Success, model);
}

Check warning on line 259 in src/Umbraco.Cms.Api.Management/Factories/DocumentPresentationFactory.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (v15/dev)

❌ New issue: Complex Method

CreateCulturePublishScheduleModels has a cyclomatic complexity of 10, threshold = 9. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using Umbraco.Cms.Api.Management.ViewModels.Document;
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Api.Management.ViewModels.Document;
using Umbraco.Cms.Api.Management.ViewModels.Document.Item;
using Umbraco.Cms.Api.Management.ViewModels.DocumentBlueprint.Item;
using Umbraco.Cms.Api.Management.ViewModels.DocumentType;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentPublishing;
using Umbraco.Cms.Core.Models.Entities;
Expand All @@ -12,10 +14,17 @@

public interface IDocumentPresentationFactory
{
[Obsolete("Schedule for removal in v17")]
Task<DocumentResponseModel> CreateResponseModelAsync(IContent content);

Task<PublishedDocumentResponseModel> CreatePublishedResponseModelAsync(IContent content);

Task<DocumentResponseModel> CreateResponseModelAsync(IContent content, ContentScheduleCollection schedule)
#pragma warning disable CS0618 // Type or member is obsolete
// Remove when obsolete CreateResponseModelAsync is removed
=> CreateResponseModelAsync(content);
#pragma warning restore CS0618 // Type or member is obsolete

DocumentItemResponseModel CreateItemResponseModel(IDocumentEntitySlim entity);

DocumentBlueprintItemResponseModel CreateBlueprintItemResponseModel(IDocumentEntitySlim entity);
Expand All @@ -24,5 +33,55 @@

DocumentTypeReferenceResponseModel CreateDocumentTypeReferenceResponseModel(IDocumentEntitySlim entity);

[Obsolete("Use CreateCulturePublishScheduleModels instead. Scheduled for removal in v17")]
Attempt<CultureAndScheduleModel, ContentPublishingOperationStatus> CreateCultureAndScheduleModel(PublishDocumentRequestModel requestModel);

Attempt<List<CulturePublishScheduleModel>, ContentPublishingOperationStatus> CreateCulturePublishScheduleModels(
PublishDocumentRequestModel requestModel)
{
// todo remove default implementation when obsolete method is removed
var model = new List<CulturePublishScheduleModel>();

foreach (CultureAndScheduleRequestModel cultureAndScheduleRequestModel in requestModel.PublishSchedules)
{
if (cultureAndScheduleRequestModel.Schedule is null)
{
model.Add(new CulturePublishScheduleModel
{
Culture = cultureAndScheduleRequestModel.Culture
?? Constants.System.InvariantCulture
});
continue;
}

if (cultureAndScheduleRequestModel.Schedule.PublishTime is not null
&& cultureAndScheduleRequestModel.Schedule.PublishTime <= StaticServiceProvider.Instance.GetRequiredService<TimeProvider>().GetUtcNow())
{
return Attempt.FailWithStatus(ContentPublishingOperationStatus.PublishTimeNeedsToBeInFuture, model);
}

if (cultureAndScheduleRequestModel.Schedule.UnpublishTime is not null
&& cultureAndScheduleRequestModel.Schedule.UnpublishTime <= StaticServiceProvider.Instance.GetRequiredService<TimeProvider>().GetUtcNow())
{
return Attempt.FailWithStatus(ContentPublishingOperationStatus.UpublishTimeNeedsToBeInFuture, model);
}

if (cultureAndScheduleRequestModel.Schedule.UnpublishTime <= cultureAndScheduleRequestModel.Schedule.PublishTime)
{
return Attempt.FailWithStatus(ContentPublishingOperationStatus.UnpublishTimeNeedsToBeAfterPublishTime, model);
}

model.Add(new CulturePublishScheduleModel
{
Culture = cultureAndScheduleRequestModel.Culture,
Schedule = new ContentScheduleModel
{
PublishDate = cultureAndScheduleRequestModel.Schedule.PublishTime,
UnpublishDate = cultureAndScheduleRequestModel.Schedule.UnpublishTime,
},
});
}

return Attempt.SucceedWithStatus(ContentPublishingOperationStatus.Success, model);
}

Check warning on line 86 in src/Umbraco.Cms.Api.Management/Factories/IDocumentPresentationFactory.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (v15/dev)

❌ New issue: Complex Method

CreateCulturePublishScheduleModels has a cyclomatic complexity of 10, threshold = 9. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public void DefineMaps(IUmbracoMapper mapper)
mapper.Define<IContent, PublishedDocumentResponseModel>((_, _) => new PublishedDocumentResponseModel(), Map);
mapper.Define<IContent, DocumentCollectionResponseModel>((_, _) => new DocumentCollectionResponseModel(), Map);
mapper.Define<IContent, DocumentBlueprintResponseModel>((_, _) => new DocumentBlueprintResponseModel(), Map);
mapper.Define<ContentScheduleCollection, DocumentResponseModel>(Map);
}

// Umbraco.Code.MapAll -Urls -Template
Expand Down Expand Up @@ -113,4 +114,26 @@ private void Map(IContent source, DocumentBlueprintResponseModel target, MapperC
documentVariantViewModel.State = DocumentVariantState.Draft;
});
}

private void Map(ContentScheduleCollection source, DocumentResponseModel target, MapperContext context)
{
foreach (ContentSchedule schedule in source.FullSchedule)
{
DocumentVariantResponseModel? variant = target.Variants.FirstOrDefault(v => v.Culture == schedule.Culture || (v.Culture.IsNullOrWhiteSpace() && schedule.Culture.IsNullOrWhiteSpace()));
if (variant is null)
{
continue;
}

switch (schedule.Action)
{
case ContentScheduleAction.Release:
variant.ScheduledPublishDate = new DateTimeOffset(schedule.Date, TimeSpan.Zero);
break;
case ContentScheduleAction.Expire:
variant.ScheduledUnpublishDate = new DateTimeOffset(schedule.Date, TimeSpan.Zero);
break;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ public class DocumentVariantResponseModel : VariantResponseModelBase
public DocumentVariantState State { get; set; }

public DateTimeOffset? PublishDate { get; set; }

public DateTimeOffset? ScheduledPublishDate { get; set; }

public DateTimeOffset? ScheduledUnpublishDate { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class CultureAndScheduleRequestModel
/// Gets or sets the schedule of publishing. Null means immediately.
/// </summary>
public ScheduleRequestModel? Schedule { get; set; }

}


Expand Down
2 changes: 2 additions & 0 deletions src/Umbraco.Core/Constants-System.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,7 @@ public static class System
/// The DataDirectory placeholder.
/// </summary>
public const string DataDirectoryPlaceholder = "|DataDirectory|";

public const string InvariantCulture = "*";
}
}
6 changes: 3 additions & 3 deletions src/Umbraco.Core/Extensions/ContentExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,20 +237,20 @@ public static ContentStatus GetStatus(this IContent content, ContentScheduleColl

if (!content.ContentType.VariesByCulture())
{
culture = string.Empty;
culture = Constants.System.InvariantCulture;
}
else if (culture.IsNullOrWhiteSpace())
{
throw new ArgumentNullException($"{nameof(culture)} cannot be null or empty");
}

IEnumerable<ContentSchedule> expires = contentSchedule.GetSchedule(culture!, ContentScheduleAction.Expire);
IEnumerable<ContentSchedule> expires = contentSchedule.GetSchedule(culture, ContentScheduleAction.Expire);
if (expires != null && expires.Any(x => x.Date > DateTime.MinValue && DateTime.Now > x.Date))
{
return ContentStatus.Expired;
}

IEnumerable<ContentSchedule> release = contentSchedule.GetSchedule(culture!, ContentScheduleAction.Release);
IEnumerable<ContentSchedule> release = contentSchedule.GetSchedule(culture, ContentScheduleAction.Release);
if (release != null && release.Any(x => x.Date > DateTime.MinValue && x.Date > DateTime.Now))
{
return ContentStatus.AwaitingRelease;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,3 @@ public class CultureAndScheduleModel
public required ISet<string> CulturesToPublishImmediately { get; set; }
public required ContentScheduleCollection Schedules { get; set; }
}


21 changes: 21 additions & 0 deletions src/Umbraco.Core/Models/ContentPublishing/CultureScheduleModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace Umbraco.Cms.Core.Models.ContentPublishing;

public class CulturePublishScheduleModel
{
/// <summary>
/// Gets or sets the culture. Null means invariant.
/// </summary>
public string? Culture { get; set; }

/// <summary>
/// Gets or sets the schedule of publishing. Null means immediately.
/// </summary>
public ContentScheduleModel? Schedule { get; set; }
}

public class ContentScheduleModel
{
public DateTimeOffset? PublishDate { get; set; }

public DateTimeOffset? UnpublishDate { get; set; }
}
Loading
Loading