-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathUmbracoContentDataListSource.cs
264 lines (227 loc) · 11.7 KB
/
UmbracoContentDataListSource.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
/* Copyright © 2020 Lee Kelleher.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.DeliveryApi;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.DynamicRoot;
using Umbraco.Cms.Core.DynamicRoot.QuerySteps;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.DeliveryApi;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.PublishedCache;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Web;
using Umbraco.Community.Contentment.Services;
using Umbraco.Extensions;
namespace Umbraco.Community.Contentment.DataEditors
{
public sealed class UmbracoContentDataListSource
: IDataListSource, IDataPickerSource, IDataSourceValueConverter, IDataSourceDeliveryApiValueConverter
{
// NOTE: Statically injected, so to preserve binary backwards-compatibility. [LK]
private readonly IApiContentBuilder _apiContentBuilder = StaticServiceProvider.Instance.GetRequiredService<IApiContentBuilder>();
private readonly IContentmentContentContext _contentmentContentContext;
private readonly IContentTypeService _contentTypeService;
private readonly IDynamicRootService _dynamicRootService;
private readonly IJsonSerializer _jsonSerializer;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly IIOHelper _ioHelper;
private const string DefaultImageAlias = "image";
public UmbracoContentDataListSource(
IContentmentContentContext contentmentContentContext,
IContentTypeService contentTypeService,
IDynamicRootService dynamicRootService,
IJsonSerializer jsonSerializer,
IUmbracoContextAccessor umbracoContextAccessor,
IIOHelper ioHelper)
{
_contentmentContentContext = contentmentContentContext;
_contentTypeService = contentTypeService;
_dynamicRootService = dynamicRootService;
_jsonSerializer = jsonSerializer;
_umbracoContextAccessor = umbracoContextAccessor;
_ioHelper = ioHelper;
}
public string Name => "Umbraco Content";
public string Description => "Select a start node to use its children as the data source.";
public string Icon => "icon-umbraco";
public Dictionary<string, object>? DefaultValues => default;
public IEnumerable<ConfigurationField> Fields => new ConfigurationField[]
{
new ConfigurationField
{
Key = "parentNode",
Name = "Parent node",
Description = "Set a parent node to use its child nodes as the data source items.",
View = _ioHelper.ResolveRelativeOrVirtualUrl(ContentPickerDataEditor.DataEditorViewPath),
},
new ConfigurationField
{
Key = "imageAlias",
Name = "Image alias",
Description = $"When using the Cards display mode, you can set a thumbnail image by enter the property alias of the media picker. The default alias is '{DefaultImageAlias}'.",
View = "textstring",
},
new ConfigurationField
{
Key = "sortAlphabetically",
Name = "Sort alphabetically?",
Description = "Select to sort the content items in alphabetical order.<br>By default, the order is defined by the Umbraco content sort order.",
View = "boolean"
},
};
public string Group => Constants.Conventions.DataSourceGroups.Umbraco;
public OverlaySize OverlaySize => OverlaySize.Small;
public IEnumerable<DataListItem> GetItems(Dictionary<string, object> config)
{
var start = GetStartContent(config);
if (start is not null)
{
var imageAlias = config.GetValueAs("imageAlias", DefaultImageAlias) ?? DefaultImageAlias;
var items = start.Children?.Select(x => ToDataListItem(x, imageAlias)) ?? Enumerable.Empty<DataListItem>();
if (config.TryGetValueAs("sortAlphabetically", out bool sortAlphabetically) == true && sortAlphabetically == true)
{
return items.OrderBy(x => x.Name, StringComparer.InvariantCultureIgnoreCase);
}
return items;
}
return Enumerable.Empty<DataListItem>();
}
public Task<IEnumerable<DataListItem>> GetItemsAsync(Dictionary<string, object> config, IEnumerable<string> values)
{
if (values?.Any() == true &&
_umbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext) == true &&
umbracoContext.Content != null)
{
var preview = true;
var imageAlias = config.GetValueAs("imageAlias", DefaultImageAlias) ?? DefaultImageAlias;
return Task.FromResult(values
.Select(x => UdiParser.TryParse(x, out GuidUdi? udi) == true ? udi : null)
.WhereNotNull()
.Select(x => umbracoContext.Content.GetById(preview, x))
.WhereNotNull()
.Select(x => ToDataListItem(x, imageAlias)));
}
return Task.FromResult(Enumerable.Empty<DataListItem>());
}
public Task<PagedResult<DataListItem>> SearchAsync(Dictionary<string, object> config, int pageNumber = 1, int pageSize = 12, string query = "")
{
var start = GetStartContent(config);
if (start != null)
{
var items = string.IsNullOrWhiteSpace(query) == false
? start.SearchChildren(query).Select(x => x.Content)
: start.Children;
if (items?.Any() == true)
{
var imageAlias = config.GetValueAs("imageAlias", DefaultImageAlias) ?? DefaultImageAlias;
var offset = (pageNumber - 1) * pageSize;
if (config.TryGetValueAs("sortAlphabetically", out bool sortAlphabetically) == true && sortAlphabetically == true)
{
items = items.OrderBy(x => x.Name, StringComparer.InvariantCultureIgnoreCase);
}
var results = new PagedResult<DataListItem>(items.Count(), pageNumber, pageSize)
{
Items = items
.Skip(offset)
.Take(pageSize)
.Select(x => ToDataListItem(x, imageAlias))
};
return Task.FromResult(results);
}
}
return Task.FromResult(new PagedResult<DataListItem>(-1, pageNumber, pageSize));
}
public Type? GetValueType(Dictionary<string, object>? config) => typeof(IPublishedContent);
public object? ConvertValue(Type type, string value)
{
return UdiParser.TryParse(value, out var udi) == true && udi is not null && _umbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext) == true
? umbracoContext.Content?.GetById(udi)
: default;
}
public Type? GetDeliveryApiValueType(Dictionary<string, object>? config) => typeof(IApiContent);
public object? ConvertToDeliveryApiValue(Type type, string value, bool expanding = false)
=> ConvertValue(type, value) is IPublishedContent content ? _apiContentBuilder.Build(content) : default;
private IPublishedContent? GetStartContent(Dictionary<string, object> config)
{
if (_umbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext) == true &&
umbracoContext.Content is IPublishedContentCache contentCache)
{
var preview = true;
var parentNode = config.GetValueAs("parentNode", string.Empty);
// Content Picker
if (UdiParser.TryParse(parentNode, out GuidUdi? udi) == true &&
udi is not null &&
udi.EntityType == UmbConstants.UdiEntityType.Document &&
udi.Guid.Equals(Guid.Empty) == false)
{
return contentCache.GetById(preview, udi.Guid);
}
// Dynamic Root
else if (parentNode?.DetectIsJson() == true)
{
var current = _contentmentContentContext.GetCurrentContent(out var isParent);
var model = _jsonSerializer.Deserialize<DynamicRoot>(parentNode);
if (model is not null)
{
var query = new DynamicRootNodeQuery
{
Context = new DynamicRootContext
{
CurrentKey = current?.Key,
ParentKey = (isParent == true ? current?.Key : current?.Parent?.Key) ?? Guid.Empty
},
OriginAlias = model.OriginAlias,
OriginKey = model.OriginKey,
QuerySteps = model.QuerySteps.Select(x => new DynamicRootQueryStep
{
Alias = x.Alias,
AnyOfDocTypeKeys = x.AnyOfDocTypeKeys
}),
};
var startNodes = _dynamicRootService.GetDynamicRootsAsync(query).GetAwaiter().GetResult();
if (startNodes?.Any() == true)
{
return contentCache.GetById(preview, startNodes.First());
}
}
}
// XPath
else if (string.IsNullOrWhiteSpace(parentNode) == false)
{
IEnumerable<string> getPath(int id) => contentCache.GetById(preview, id)?.Path.ToDelimitedList().Reverse() ?? UmbConstants.System.RootString.AsEnumerableOfOne();
bool publishedContentExists(int id) => contentCache.GetById(preview, id) != null;
var parsed = _contentmentContentContext.ParseXPathQuery(parentNode, getPath, publishedContentExists);
if (string.IsNullOrWhiteSpace(parsed) == false && parsed.StartsWith('$') == false)
{
#pragma warning disable CS0618 // Type or member is obsolete
return contentCache.GetSingleByXPath(preview, parsed);
#pragma warning restore CS0618 // Type or member is obsolete
}
}
}
return default;
}
private DataListItem ToDataListItem(IPublishedContent content, string imageAlias = DefaultImageAlias)
{
return new DataListItem
{
Name = content.Name,
Description = content.TemplateId > 0 ? content.Url() : string.Empty,
Disabled = content.IsPublished() == false,
Icon = content.ContentType.GetIcon(_contentTypeService),
Properties = new Dictionary<string, object>
{
{ DefaultImageAlias, content.Value<IPublishedContent>(imageAlias)?.Url() ?? string.Empty },
},
Value = content.GetUdi().ToString(),
};
}
}
}