-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathContentPublishingService.cs
469 lines (409 loc) · 21.4 KB
/
ContentPublishingService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.ContentPublishing;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Services.OperationStatus;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Services;
internal sealed class ContentPublishingService : IContentPublishingService
{
private readonly ICoreScopeProvider _coreScopeProvider;
private readonly IContentService _contentService;
private readonly IUserIdKeyResolver _userIdKeyResolver;
private readonly IContentValidationService _contentValidationService;
private readonly IContentTypeService _contentTypeService;
private readonly ILanguageService _languageService;
private ContentSettings _contentSettings;
private readonly IRelationService _relationService;
public ContentPublishingService(
ICoreScopeProvider coreScopeProvider,
IContentService contentService,
IUserIdKeyResolver userIdKeyResolver,
IContentValidationService contentValidationService,
IContentTypeService contentTypeService,
ILanguageService languageService,
IOptionsMonitor<ContentSettings> optionsMonitor,
IRelationService relationService)
{
_coreScopeProvider = coreScopeProvider;
_contentService = contentService;
_userIdKeyResolver = userIdKeyResolver;
_contentValidationService = contentValidationService;
_contentTypeService = contentTypeService;
_languageService = languageService;
_relationService = relationService;
_contentSettings = optionsMonitor.CurrentValue;
optionsMonitor.OnChange((contentSettings) =>
{
_contentSettings = contentSettings;
});
}
/// <inheritdoc />
public async Task<Attempt<ContentPublishingResult, ContentPublishingOperationStatus>> PublishAsync(
Guid key,
ICollection<CulturePublishScheduleModel> culturesToPublishOrSchedule,
Guid userKey)
{
var culturesToPublishImmediately =
culturesToPublishOrSchedule.Where(culture => culture.Schedule is null).Select(c => c.Culture ?? "*").ToHashSet();
ContentScheduleCollection schedules = _contentService.GetContentScheduleByContentId(key);
foreach (CulturePublishScheduleModel cultureToSchedule in culturesToPublishOrSchedule.Where(c => c.Schedule is not null))
{
var culture = cultureToSchedule.Culture ?? "*";
if (cultureToSchedule.Schedule!.PublishDate is null)
{
schedules.RemoveIfExists(culture, ContentScheduleAction.Release);
}
else
{
schedules.AddOrUpdate(culture, cultureToSchedule.Schedule!.PublishDate.Value.UtcDateTime, ContentScheduleAction.Release);
}
if (cultureToSchedule.Schedule!.UnpublishDate is null)
{
schedules.RemoveIfExists(culture, ContentScheduleAction.Expire);
}
else
{
schedules.AddOrUpdate(culture, cultureToSchedule.Schedule!.UnpublishDate.Value.UtcDateTime, ContentScheduleAction.Expire);
}
}
var cultureAndSchedule = new CultureAndScheduleModel
{
CulturesToPublishImmediately = culturesToPublishImmediately,
Schedules = schedules,
};
return await PublishAsync(key, cultureAndSchedule, userKey);
}
/// <inheritdoc />
[Obsolete("Use non obsoleted version instead. Scheduled for removal in v17")]
public async Task<Attempt<ContentPublishingResult, ContentPublishingOperationStatus>> PublishAsync(
Guid key,
CultureAndScheduleModel cultureAndSchedule,
Guid userKey)
{
using ICoreScope scope = _coreScopeProvider.CreateCoreScope();
IContent? content = _contentService.GetById(key);
if (content is null)
{
scope.Complete();
return Attempt.FailWithStatus(ContentPublishingOperationStatus.ContentNotFound, new ContentPublishingResult());
}
// If nothing is requested for publish or scheduling, clear all schedules and publish nothing.
if (cultureAndSchedule.CulturesToPublishImmediately.Count == 0 &&
cultureAndSchedule.Schedules.FullSchedule.Count == 0)
{
_contentService.PersistContentSchedule(content, cultureAndSchedule.Schedules);
scope.Complete();
return Attempt.SucceedWithStatus(
ContentPublishingOperationStatus.Success,
new ContentPublishingResult { Content = content });
}
ISet<string> culturesToPublishImmediately = cultureAndSchedule.CulturesToPublishImmediately;
var cultures =
culturesToPublishImmediately.Union(
cultureAndSchedule.Schedules.FullSchedule.Select(x => x.Culture)).ToArray();
// If cultures are provided for non variant content, and they include the default culture, consider
// the request as valid for publishing the content.
// This is necessary as in a bulk publishing context the cultures are selected and provided from the
// list of languages.
bool variesByCulture = content.ContentType.VariesByCulture();
if (!variesByCulture)
{
ILanguage? defaultLanguage = await _languageService.GetDefaultLanguageAsync();
if (defaultLanguage is not null)
{
if (cultures.Contains(defaultLanguage.IsoCode))
{
cultures = ["*"];
}
if (culturesToPublishImmediately.Contains(defaultLanguage.IsoCode))
{
culturesToPublishImmediately = new HashSet<string> { "*" };
}
}
}
if (variesByCulture)
{
if (cultures.Any() is false)
{
scope.Complete();
return Attempt.FailWithStatus(ContentPublishingOperationStatus.CultureMissing, new ContentPublishingResult());
}
if (cultures.Any(x => x == "*"))
{
scope.Complete();
return Attempt.FailWithStatus(ContentPublishingOperationStatus.CannotPublishInvariantWhenVariant, new ContentPublishingResult());
}
IEnumerable<string> validCultures = (await _languageService.GetAllAsync()).Select(x => x.IsoCode);
if (validCultures.ContainsAll(cultures) is false)
{
scope.Complete();
return Attempt.FailWithStatus(ContentPublishingOperationStatus.InvalidCulture, new ContentPublishingResult());
}
}
else
{
if (cultures.Length != 1 || cultures.Any(x => x != "*"))
{
scope.Complete();
return Attempt.FailWithStatus(ContentPublishingOperationStatus.InvalidCulture, new ContentPublishingResult());
}
}
ContentValidationResult validationResult = await ValidateCurrentContentAsync(content, cultures);
if (validationResult.ValidationErrors.Any())
{
scope.Complete();
return Attempt.FailWithStatus(ContentPublishingOperationStatus.ContentInvalid, new ContentPublishingResult
{
Content = content,
InvalidPropertyAliases = validationResult.ValidationErrors.Select(property => property.Alias).ToArray()
});
}
var userId = await _userIdKeyResolver.GetAsync(userKey);
PublishResult? result = null;
if (culturesToPublishImmediately.Any())
{
result = _contentService.Publish(content, culturesToPublishImmediately.ToArray(), userId);
}
if (result?.Success != false && cultureAndSchedule.Schedules.FullSchedule.Any())
{
_contentService.PersistContentSchedule(result?.Content ?? content, cultureAndSchedule.Schedules);
result = new PublishResult(
PublishResultType.SuccessPublish,
result?.EventMessages ?? new EventMessages(),
result?.Content ?? content);
}
scope.Complete();
if (result is null)
{
return Attempt.FailWithStatus(ContentPublishingOperationStatus.NothingToPublish, new ContentPublishingResult());
}
ContentPublishingOperationStatus contentPublishingOperationStatus = ToContentPublishingOperationStatus(result);
return contentPublishingOperationStatus is ContentPublishingOperationStatus.Success
? Attempt.SucceedWithStatus(
ToContentPublishingOperationStatus(result),
new ContentPublishingResult { Content = content })
: Attempt.FailWithStatus(ToContentPublishingOperationStatus(result), new ContentPublishingResult
{
Content = content,
InvalidPropertyAliases = result.InvalidProperties?.Select(property => property.Alias).ToArray()
?? Enumerable.Empty<string>()
});
}
private async Task<ContentValidationResult> ValidateCurrentContentAsync(IContent content, string[] cultures)
{
// Would be better to be able to use a mapper/factory, but currently all that functionality is very much presentation logic.
var model = new ContentUpdateModel()
{
InvariantName = content.Name,
// NOTE KJA: this needs redoing; we need to make an informed decision whether to include invariant properties, depending on if editing invariant properties is allowed on all variants, or if the default language is included in cultures
InvariantProperties = content.Properties.Where(x => x.PropertyType.VariesByCulture() is false).Select(x => new PropertyValueModel()
{
Alias = x.Alias,
Value = x.GetValue()
}),
Variants = cultures.Select(culture => new VariantModel()
{
Name = content.GetPublishName(culture) ?? string.Empty,
Culture = culture,
Segment = null,
Properties = content.Properties.Where(prop => prop.PropertyType.VariesByCulture()).Select(prop => new PropertyValueModel()
{
Alias = prop.Alias,
Value = prop.GetValue(culture: culture, segment: null, published: false)
})
})
};
IContentType? contentType = _contentTypeService.Get(content.ContentType.Key)!;
ContentValidationResult validationResult = await _contentValidationService.ValidatePropertiesAsync(model, contentType, cultures);
return validationResult;
}
/// <inheritdoc />
[Obsolete("This method is not longer used as the 'force' parameter has been split into publishing unpublished and force re-published. Please use the overload containing parameters for those options instead. Will be removed in V17.")]
public async Task<Attempt<ContentPublishingBranchResult, ContentPublishingOperationStatus>> PublishBranchAsync(Guid key, IEnumerable<string> cultures, bool force, Guid userKey)
=> await PublishBranchAsync(key, cultures, force ? PublishBranchFilter.IncludeUnpublished : PublishBranchFilter.Default, userKey);
/// <inheritdoc />
public async Task<Attempt<ContentPublishingBranchResult, ContentPublishingOperationStatus>> PublishBranchAsync(Guid key, IEnumerable<string> cultures, PublishBranchFilter publishBranchFilter, Guid userKey)
{
using ICoreScope scope = _coreScopeProvider.CreateCoreScope();
IContent? content = _contentService.GetById(key);
if (content is null)
{
return Attempt.FailWithStatus(
ContentPublishingOperationStatus.ContentNotFound,
new ContentPublishingBranchResult
{
FailedItems = new[]
{
new ContentPublishingBranchItemResult
{
Key = key, OperationStatus = ContentPublishingOperationStatus.ContentNotFound
}
}
});
}
var userId = await _userIdKeyResolver.GetAsync(userKey);
IEnumerable<PublishResult> result = _contentService.PublishBranch(content, publishBranchFilter, cultures.ToArray(), userId);
scope.Complete();
var itemResults = result.ToDictionary(r => r.Content.Key, ToContentPublishingOperationStatus);
var branchResult = new ContentPublishingBranchResult
{
Content = content,
SucceededItems = itemResults
.Where(i => i.Value is ContentPublishingOperationStatus.Success)
.Select(i => new ContentPublishingBranchItemResult { Key = i.Key, OperationStatus = i.Value })
.ToArray(),
FailedItems = itemResults
.Where(i => i.Value is not ContentPublishingOperationStatus.Success)
.Select(i => new ContentPublishingBranchItemResult { Key = i.Key, OperationStatus = i.Value })
.ToArray()
};
return branchResult.FailedItems.Any() is false
? Attempt.SucceedWithStatus(ContentPublishingOperationStatus.Success, branchResult)
: Attempt.FailWithStatus(ContentPublishingOperationStatus.FailedBranch, branchResult);
}
/// <inheritdoc/>
public async Task<Attempt<ContentPublishingOperationStatus>> UnpublishAsync(Guid key, ISet<string>? cultures, Guid userKey)
{
using ICoreScope scope = _coreScopeProvider.CreateCoreScope();
IContent? content = _contentService.GetById(key);
if (content is null)
{
scope.Complete();
return Attempt.Fail(ContentPublishingOperationStatus.ContentNotFound);
}
if (_contentSettings.DisableUnpublishWhenReferenced && _relationService.IsRelated(content.Id))
{
scope.Complete();
return Attempt<ContentPublishingOperationStatus>.Fail(ContentPublishingOperationStatus.CannotUnpublishWhenReferenced);
}
var userId = await _userIdKeyResolver.GetAsync(userKey);
// If cultures are provided for non variant content, and they include the default culture, consider
// the request as valid for unpublishing the content.
// This is necessary as in a bulk unpublishing context the cultures are selected and provided from the
// list of languages.
if (cultures is not null && !content.ContentType.VariesByCulture())
{
ILanguage? defaultLanguage = await _languageService.GetDefaultLanguageAsync();
if (defaultLanguage is not null && cultures.Contains(defaultLanguage.IsoCode))
{
cultures = null;
}
}
Attempt<ContentPublishingOperationStatus> attempt;
if (cultures is null)
{
attempt = await UnpublishInvariantAsync(
content,
userId);
scope.Complete();
return attempt;
}
if (cultures.Any() is false)
{
scope.Complete();
return Attempt<ContentPublishingOperationStatus>.Fail(ContentPublishingOperationStatus.CultureMissing);
}
if (cultures.Contains("*"))
{
attempt = await UnpublishAllCulturesAsync(
content,
userId);
}
else
{
attempt = await UnpublishMultipleCultures(
content,
cultures,
userId);
}
scope.Complete();
return attempt;
}
private Task<Attempt<ContentPublishingOperationStatus>> UnpublishAllCulturesAsync(IContent content, int userId)
{
if (content.ContentType.VariesByCulture() is false)
{
return Task.FromResult(Attempt.Fail(ContentPublishingOperationStatus.CannotPublishVariantWhenNotVariant));
}
using ICoreScope scope = _coreScopeProvider.CreateCoreScope();
PublishResult result = _contentService.Unpublish(content, "*", userId);
scope.Complete();
ContentPublishingOperationStatus contentPublishingOperationStatus = ToContentPublishingOperationStatus(result);
return Task.FromResult(contentPublishingOperationStatus is ContentPublishingOperationStatus.Success
? Attempt.Succeed(ToContentPublishingOperationStatus(result))
: Attempt.Fail(ToContentPublishingOperationStatus(result)));
}
private async Task<Attempt<ContentPublishingOperationStatus>> UnpublishMultipleCultures(IContent content, ISet<string> cultures, int userId)
{
using ICoreScope scope = _coreScopeProvider.CreateCoreScope();
if (content.ContentType.VariesByCulture() is false)
{
scope.Complete();
return Attempt.Fail(ContentPublishingOperationStatus.CannotPublishVariantWhenNotVariant);
}
var validCultures = (await _languageService.GetAllAsync()).Select(x => x.IsoCode).ToArray();
foreach (var culture in cultures)
{
if (validCultures.Contains(culture) is false)
{
scope.Complete();
return Attempt.Fail(ContentPublishingOperationStatus.InvalidCulture);
}
PublishResult result = _contentService.Unpublish(content, culture, userId);
ContentPublishingOperationStatus contentPublishingOperationStatus = ToContentPublishingOperationStatus(result);
if (contentPublishingOperationStatus is not ContentPublishingOperationStatus.Success)
{
return Attempt.Fail(ToContentPublishingOperationStatus(result));
}
}
scope.Complete();
return Attempt.Succeed(ContentPublishingOperationStatus.Success);
}
private Task<Attempt<ContentPublishingOperationStatus>> UnpublishInvariantAsync(IContent content, int userId)
{
using ICoreScope scope = _coreScopeProvider.CreateCoreScope();
if (content.ContentType.VariesByCulture())
{
return Task.FromResult(Attempt.Fail(ContentPublishingOperationStatus.CannotPublishInvariantWhenVariant));
}
PublishResult result = _contentService.Unpublish(content, null, userId);
scope.Complete();
ContentPublishingOperationStatus contentPublishingOperationStatus = ToContentPublishingOperationStatus(result);
return Task.FromResult(contentPublishingOperationStatus is ContentPublishingOperationStatus.Success
? Attempt.Succeed(ToContentPublishingOperationStatus(result))
: Attempt.Fail(ToContentPublishingOperationStatus(result)));
}
private static ContentPublishingOperationStatus ToContentPublishingOperationStatus(PublishResult publishResult)
=> publishResult.Result switch
{
PublishResultType.SuccessPublish => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessPublishCulture => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessPublishAlready => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessUnpublish => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessUnpublishAlready => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessUnpublishCulture => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessUnpublishMandatoryCulture => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessUnpublishLastCulture => ContentPublishingOperationStatus.Success,
PublishResultType.SuccessMixedCulture => ContentPublishingOperationStatus.Success,
// PublishResultType.FailedPublish => expr, <-- never used directly in a PublishResult
PublishResultType.FailedPublishPathNotPublished => ContentPublishingOperationStatus.PathNotPublished,
PublishResultType.FailedPublishHasExpired => ContentPublishingOperationStatus.HasExpired,
PublishResultType.FailedPublishAwaitingRelease => ContentPublishingOperationStatus.AwaitingRelease,
PublishResultType.FailedPublishCultureHasExpired => ContentPublishingOperationStatus.CultureHasExpired,
PublishResultType.FailedPublishCultureAwaitingRelease => ContentPublishingOperationStatus.CultureAwaitingRelease,
PublishResultType.FailedPublishIsTrashed => ContentPublishingOperationStatus.InTrash,
PublishResultType.FailedPublishCancelledByEvent => ContentPublishingOperationStatus.CancelledByEvent,
PublishResultType.FailedPublishContentInvalid => ContentPublishingOperationStatus.ContentInvalid,
PublishResultType.FailedPublishNothingToPublish => ContentPublishingOperationStatus.NothingToPublish,
PublishResultType.FailedPublishMandatoryCultureMissing => ContentPublishingOperationStatus.MandatoryCultureMissing,
PublishResultType.FailedPublishConcurrencyViolation => ContentPublishingOperationStatus.ConcurrencyViolation,
PublishResultType.FailedPublishUnsavedChanges => ContentPublishingOperationStatus.UnsavedChanges,
PublishResultType.FailedUnpublish => ContentPublishingOperationStatus.Failed,
PublishResultType.FailedUnpublishCancelledByEvent => ContentPublishingOperationStatus.CancelledByEvent,
_ => throw new ArgumentOutOfRangeException()
};
}