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

Merged
merged 22 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
49760f6
Expose schedule date for on document get endpoint
Migaroez Nov 7, 2024
366d2ff
typo fix
Migaroez Nov 7, 2024
4b457c0
stupid stuff
Migaroez Nov 7, 2024
114d53d
Enable content scheduling features in the publishing service
Migaroez Nov 14, 2024
dcf8e86
Replace obsoleted non async calls
Migaroez Nov 14, 2024
7094855
Add content scheduling test
Migaroez Nov 14, 2024
c05aaeb
Publush and schedule combination test
Migaroez Nov 15, 2024
73b9786
More invariantCulture notation allignment and more tests
Migaroez Nov 18, 2024
dd0bd78
Link up api with updated document scheduling
Migaroez Nov 18, 2024
7d5779b
Merge branch 'v15/dev' into v15/task/improve-document-schedule
Migaroez Nov 18, 2024
e98f25b
More invariant culture notation allignment
Migaroez Nov 18, 2024
2b93255
Fix breaking change
Migaroez Nov 18, 2024
9130fb2
Merge branch 'v15/dev' into v15/task/improve-document-schedule
Migaroez Nov 19, 2024
3b9f14d
Merge branch 'v15/dev' into v15/task/improve-document-schedule
bergmania Nov 25, 2024
75079b2
Return expected status codes.
bergmania Nov 25, 2024
dbb78a8
Merge branch 'v15/dev' into v15/task/improve-document-schedule
bergmania Nov 25, 2024
afabd09
Fix constructor
bergmania Nov 25, 2024
14adaff
Forward Default implementation to actual core implementation
Migaroez Nov 26, 2024
32faaeb
Forward default implementation to core implementation
Migaroez Nov 26, 2024
1320eae
Make content with scheduling retrieval scope safe
Migaroez Nov 26, 2024
bba69f3
Merge branch 'v15/dev' into v15/task/improve-document-schedule
bergmania Nov 28, 2024
b46d163
Merge branch 'v15/dev' into v15/task/improve-document-schedule
Migaroez Jan 8, 2025
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,13 +2,14 @@
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.Models;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Security.Authorization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Services.Querying;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Extensions;

Expand All @@ -18,17 +19,42 @@ namespace Umbraco.Cms.Api.Management.Controllers.Document;
public class ByKeyDocumentController : DocumentControllerBase
{
private readonly IAuthorizationService _authorizationService;
private readonly IContentEditingService _contentEditingService;
private readonly IDocumentPresentationFactory _documentPresentationFactory;
private readonly IContentQueryService _contentQueryService;

[Obsolete("Scheduled for removal in v17")]
public ByKeyDocumentController(
IAuthorizationService authorizationService,
IContentEditingService contentEditingService,
IDocumentPresentationFactory documentPresentationFactory)
{
_authorizationService = authorizationService;
_contentEditingService = contentEditingService;
_documentPresentationFactory = documentPresentationFactory;
_contentQueryService = StaticServiceProvider.Instance.GetRequiredService<IContentQueryService>();
}

// needed for greedy selection until other constructor remains in v17
[Obsolete("Scheduled for removal in v17")]
public ByKeyDocumentController(
IAuthorizationService authorizationService,
IContentEditingService contentEditingService,
IDocumentPresentationFactory documentPresentationFactory,
IContentQueryService contentQueryService)
{
_authorizationService = authorizationService;
_documentPresentationFactory = documentPresentationFactory;
_contentQueryService = contentQueryService;
}

[ActivatorUtilitiesConstructor]
public ByKeyDocumentController(
IAuthorizationService authorizationService,
IDocumentPresentationFactory documentPresentationFactory,
IContentQueryService contentQueryService)
{
_authorizationService = authorizationService;
_documentPresentationFactory = documentPresentationFactory;
_contentQueryService = contentQueryService;
}

[HttpGet("{id:guid}")]
Expand All @@ -47,13 +73,16 @@ public async Task<IActionResult> ByKey(CancellationToken cancellationToken, Guid
return Forbidden();
}

IContent? content = await _contentEditingService.GetAsync(id);
if (content == null)
var contentWithScheduleAttempt = await _contentQueryService.GetWithSchedulesAsync(id);

if (contentWithScheduleAttempt.Success == false)
{
return DocumentNotFound();
return ContentQueryOperationStatusResult(contentWithScheduleAttempt.Status);
}

DocumentResponseModel model = await _documentPresentationFactory.CreateResponseModelAsync(content);
DocumentResponseModel model = await _documentPresentationFactory.CreateResponseModelAsync(
contentWithScheduleAttempt.Result!.Content,
contentWithScheduleAttempt.Result.Schedules);
return Ok(model);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,15 @@ protected IActionResult PublicAccessOperationStatusResult(PublicAccessOperationS
.WithTitle("Unknown content operation status.")
.Build()),
});

protected IActionResult ContentQueryOperationStatusResult(ContentQueryOperationStatus status)
=> OperationStatusResult(status, problemDetailsBuilder => status switch
{
ContentQueryOperationStatus.ContentNotFound => NotFound(problemDetailsBuilder
.WithTitle("The document could not be found")
.Build()),
_ => StatusCode(StatusCodes.Status500InternalServerError, problemDetailsBuilder
.WithTitle("Unknown content query status.")
.Build()),
});
}
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.30 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 @@ -40,6 +40,7 @@
_idKeyMap = idKeyMap;
}

[Obsolete("Schedule for removal in v17")]
public async Task<DocumentResponseModel> CreateResponseModelAsync(IContent content)
{
DocumentResponseModel responseModel = _umbracoMapper.Map<DocumentResponseModel>(content)!;
Expand Down Expand Up @@ -74,6 +75,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)
{
Attempt<Guid> parentKeyAttempt = _idKeyMap.GetKeyForId(entity.ParentId, UmbracoObjectTypes.Document);
Expand Down Expand Up @@ -135,6 +154,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 @@ -143,7 +163,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 @@ -159,7 +179,7 @@
}

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

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

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 264 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 = "*";
}
}
2 changes: 2 additions & 0 deletions src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
using Umbraco.Cms.Core.Services.FileSystem;
using Umbraco.Cms.Core.Services.ImportExport;
using Umbraco.Cms.Core.Services.Navigation;
using Umbraco.Cms.Core.Services.Querying;
using Umbraco.Cms.Core.Services.Querying.RecycleBin;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Core.Telemetry;
Expand Down Expand Up @@ -418,6 +419,7 @@
// Add Query services
Services.AddUnique<IDocumentRecycleBinQueryService, DocumentRecycleBinQueryService>();
Services.AddUnique<IMediaRecycleBinQueryService, MediaRecycleBinQueryService>();
Services.AddUnique<IContentQueryService, ContentQueryService>();

Check warning on line 422 in src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs

View check run for this annotation

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

❌ Getting worse: Large Method

AddCoreServices increases from 200 to 201 lines of code, threshold = 70. Large functions with many lines of code are generally harder to understand and lower the code health. Avoid adding more lines to this function.

// Authorizers
Services.AddSingleton<IAuthorizationHelper, AuthorizationHelper>();
Expand Down
Loading
Loading