-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathDefaultProvider.cs
More file actions
432 lines (391 loc) · 18.2 KB
/
DefaultProvider.cs
File metadata and controls
432 lines (391 loc) · 18.2 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using DD4T.ContentModel;
using DD4T.ContentModel.Factories;
using Sdl.Web.Common;
using Sdl.Web.Common.Configuration;
using Sdl.Web.Common.Interfaces;
using Sdl.Web.Common.Logging;
using Sdl.Web.Common.Models;
using Sdl.Web.Tridion.Statics;
using Sdl.Web.Mvc.Configuration;
using Sdl.Web.Tridion.Query;
using Tridion.ContentDelivery.DynamicContent.Query;
using Tridion.ContentDelivery.Meta;
using IItem = Tridion.ContentDelivery.Meta.IItem;
using IPage = DD4T.ContentModel.IPage;
namespace Sdl.Web.Tridion.Mapping
{
/// <summary>
/// Default Content Provider and Navigation Provider implementation (DD4T-based).
/// </summary>
public class DefaultProvider : IContentProvider, INavigationProvider
{
#region IContentProvider members
#pragma warning disable 618
[Obsolete("Deprecated in DXA 1.1. Use SiteConfiguration.LinkResolver or SiteConfiguration.RichTextProcessor to get the new extension points.")]
public IContentResolver ContentResolver
{
get
{
return new LegacyContentResolverFacade();
}
set
{
throw new NotSupportedException("Setting this property is not supported in DXA 1.1.");
}
}
/// <summary>
/// Gets a Page Model for a given URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="addIncludes">Indicates whether include Pages should be expanded.</param>
/// <returns>The Page Model.</returns>
[Obsolete("Deprecated in DXA 1.1. Use the overload that has a Localization parameter.")]
public PageModel GetPageModel(string url, bool addIncludes = true)
{
return GetPageModel(url, WebRequestContext.Localization, addIncludes);
}
/// <summary>
/// Populates a Content List by executing the query it specifies.
/// </summary>
/// <param name="contentList">The Content List (of Teasers) which specifies the query and is to be populated.</param>
[Obsolete("Deprecated in DXA 1.1. Use the overload that has a Localization parameter.")]
public ContentList<Teaser> PopulateDynamicList(ContentList<Teaser> contentList)
{
PopulateDynamicList(contentList, WebRequestContext.Localization);
return contentList;
}
#pragma warning restore 618
/// <summary>
/// Gets a Page Model for a given URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="localization">The context Localization.</param>
/// <param name="addIncludes">Indicates whether include Pages should be expanded.</param>
/// <returns>The Page Model.</returns>
/// <exception cref="DxaItemNotFoundException">If no Page Model exists for the given URL.</exception>
public virtual PageModel GetPageModel(string url, Localization localization, bool addIncludes)
{
using (new Tracer(url, localization, addIncludes))
{
//We can have a couple of tries to get the page model if there is no file extension on the url request, but it does not end in a slash:
//1. Try adding the default extension, so /news becomes /news.html
IPage page = GetPage(url, localization);
if (page == null && (url == null || (!url.EndsWith("/") && url.LastIndexOf(".", StringComparison.Ordinal) <= url.LastIndexOf("/", StringComparison.Ordinal))))
{
//2. Try adding the default page, so /news becomes /news/index.html
page = GetPage(url + "/", localization);
}
if (page == null)
{
throw new DxaItemNotFoundException(url);
}
FullyLoadDynamicComponentPresentations(page, localization);
IPage[] includes = addIncludes ? GetIncludesFromModel(page, localization).ToArray() : new IPage[0];
return ModelBuilderPipeline.CreatePageModel(page, includes, localization);
}
}
/// <summary>
/// Gets an Entity Model for a given Entity Identifier.
/// </summary>
/// <param name="id">The Entity Identifier in format ComponentID-TemplateID.</param>
/// <param name="localization">The context Localization.</param>
/// <returns>The Entity Model.</returns>
/// <exception cref="DxaItemNotFoundException">If no Entity Model exists for the given URL.</exception>
/// <remarks>
/// Since we can't obtain CT metadata for DCPs, we obtain the View Name from the CT Title.
/// </remarks>
public virtual EntityModel GetEntityModel(string id, Localization localization)
{
using (new Tracer(id, localization))
{
string[] idParts = id.Split('-');
if (idParts.Length != 2)
{
throw new DxaException(String.Format("Invalid Entity Identifier '{0}'. Must be in format ComponentID-TemplateID.", id));
}
string componentUri = string.Format("tcm:{0}-{1}", localization.LocalizationId, idParts[0]);
string templateUri = string.Format("tcm:{0}-{1}-32", localization.LocalizationId, idParts[1]);
IComponentPresentationFactory componentPresentationFactory = DD4TFactoryCache.GetComponentPresentationFactory(localization);
IComponentPresentation dcp;
if (!componentPresentationFactory.TryGetComponentPresentation(out dcp, componentUri, templateUri))
{
throw new DxaItemNotFoundException(id);
}
return ModelBuilderPipeline.CreateEntityModel(dcp, localization);
}
}
/// <summary>
/// Gets a Static Content Item for a given URL path.
/// </summary>
/// <param name="urlPath">The URL path.</param>
/// <param name="localization">The context Localization.</param>
/// <returns>The Static Content Item.</returns>
public StaticContentItem GetStaticContentItem(string urlPath, Localization localization)
{
using (new Tracer(urlPath, localization))
{
string localFilePath = BinaryFileManager.Instance.GetCachedFile(urlPath, localization);
return new StaticContentItem(
new FileStream(localFilePath, FileMode.Open),
MimeMapping.GetMimeMapping(localFilePath),
File.GetLastWriteTime(localFilePath),
Encoding.UTF8
);
}
}
/// <summary>
/// Populates a Content List (of Teasers) by executing the query it specifies.
/// </summary>
/// <param name="contentList">The Content List which specifies the query and is to be populated.</param>
/// <param name="localization">The context Localization.</param>
public virtual void PopulateDynamicList<T>(ContentList<T> contentList, Localization localization) where T : EntityModel
{
using (new Tracer(contentList, localization))
{
BrokerQuery query = new BrokerQuery
{
Start = contentList.Start,
PublicationId = Int32.Parse(localization.LocalizationId),
PageSize = contentList.PageSize,
SchemaId = MapSchema(contentList.ContentType.Key, localization),
Sort = contentList.Sort.Key
};
// TODO: For now BrokerQuery always returns Teasers
IEnumerable<Teaser> queryResults = query.ExecuteQuery();
ILinkResolver linkResolver = SiteConfiguration.LinkResolver;
foreach (Teaser item in queryResults)
{
item.Link.Url = linkResolver.ResolveLink(item.Link.Url, localization: localization);
}
contentList.ItemListElements = queryResults.Cast<T>().ToList();
contentList.HasMore = query.HasMore;
}
}
#endregion
#region INavigationProvider Members
/// <summary>
/// Gets the Navigation Model (Sitemap) for a given Localization.
/// </summary>
/// <param name="localization">The Localization.</param>
/// <returns>The Navigation Model (Sitemap root Item).</returns>
public virtual SitemapItem GetNavigationModel(Localization localization)
{
using (new Tracer(localization))
{
string url = SiteConfiguration.LocalizeUrl("navigation.json", localization);
// TODO TSI-110: This is a temporary measure to cache the Navigation Model per request to not retrieve and serialize 3 times per request. Comprehensive caching strategy pending
string cacheKey = "navigation-" + url;
SitemapItem result;
if (HttpContext.Current.Items[cacheKey] == null)
{
Log.Debug("Deserializing Navigation Model from raw content URL '{0}'", url);
string navigationJsonString = GetPageContent(url, localization);
result = new JavaScriptSerializer().Deserialize<SitemapItem>(navigationJsonString);
HttpContext.Current.Items[cacheKey] = result;
}
else
{
Log.Debug("Obtained Navigation Model from cache.");
result = (SitemapItem)HttpContext.Current.Items[cacheKey];
}
return result;
}
}
/// <summary>
/// Gets Navigation Links for the top navigation menu for the given request URL path.
/// </summary>
/// <param name="requestUrlPath">The request URL path.</param>
/// <param name="localization">The Localization.</param>
/// <returns>The Navigation Links.</returns>
public virtual NavigationLinks GetTopNavigationLinks(string requestUrlPath, Localization localization)
{
using (new Tracer(requestUrlPath, localization))
{
NavigationLinks navigationLinks = new NavigationLinks();
SitemapItem sitemapRoot = GetNavigationModel(localization);
foreach (SitemapItem item in sitemapRoot.Items.Where(i => i.Visible))
{
navigationLinks.Items.Add(CreateLink((item.Title == "Index") ? sitemapRoot : item));
}
return navigationLinks;
}
}
/// <summary>
/// Gets Navigation Links for the context navigation panel for the given request URL path.
/// </summary>
/// <param name="requestUrlPath">The request URL path.</param>
/// <param name="localization">The Localization.</param>
/// <returns>The Navigation Links.</returns>
public virtual NavigationLinks GetContextNavigationLinks(string requestUrlPath, Localization localization)
{
using (new Tracer(requestUrlPath, localization))
{
NavigationLinks navigationLinks = new NavigationLinks();
SitemapItem sitemapItem = GetNavigationModel(localization); // Start with Sitemap root Item.
int levels = requestUrlPath.Split('/').Length;
while (levels > 1 && sitemapItem.Items != null)
{
SitemapItem newParent = sitemapItem.Items.FirstOrDefault(i => i.Type == "StructureGroup" && requestUrlPath.StartsWith(i.Url, StringComparison.InvariantCultureIgnoreCase));
if (newParent == null)
{
break;
}
sitemapItem = newParent;
}
if (sitemapItem != null && sitemapItem.Items != null)
{
foreach (SitemapItem item in sitemapItem.Items.Where(i => i.Visible))
{
navigationLinks.Items.Add(CreateLink(item));
}
}
return navigationLinks;
}
}
/// <summary>
/// Gets Navigation Links for the breadcrumb trail for the given request URL path.
/// </summary>
/// <param name="requestUrlPath">The request URL path.</param>
/// <param name="localization">The Localization.</param>
/// <returns>The Navigation Links.</returns>
public virtual NavigationLinks GetBreadcrumbNavigationLinks(string requestUrlPath, Localization localization)
{
using (new Tracer(requestUrlPath, localization))
{
NavigationLinks navigationLinks = new NavigationLinks();
int levels = requestUrlPath.Split('/').Length;
SitemapItem sitemapItem = GetNavigationModel(localization); // Start with Sitemap root Item.
navigationLinks.Items.Add(CreateLink(sitemapItem));
while (levels > 1 && sitemapItem.Items != null)
{
sitemapItem = sitemapItem.Items.FirstOrDefault(i => requestUrlPath.StartsWith(i.Url, StringComparison.InvariantCultureIgnoreCase));
if (sitemapItem != null)
{
navigationLinks.Items.Add(CreateLink(sitemapItem));
levels--;
}
else
{
break;
}
}
return navigationLinks;
}
}
#endregion
/// <summary>
/// Creates a Link Entity Model out of a SitemapItem Entity Model.
/// </summary>
/// <param name="sitemapItem">The SitemapItem Entity Model.</param>
/// <returns>The Link Entity Model.</returns>
protected static Link CreateLink(SitemapItem sitemapItem)
{
string url = sitemapItem.Url;
if (url.StartsWith("tcm:"))
{
url = SiteConfiguration.LinkResolver.ResolveLink(url);
}
return new Link
{
Url = url,
LinkText = sitemapItem.Title
};
}
/// <summary>
/// Converts a request URL into a CMS URL (for example adding default page name, and file extension)
/// </summary>
/// <param name="url">The request URL</param>
/// <returns>A CMS URL</returns>
protected virtual string GetCmUrl(string url)
{
if (String.IsNullOrEmpty(url))
{
url = Constants.DefaultPageName;
}
if (url.EndsWith("/"))
{
url = url + Constants.DefaultPageName;
}
if (!Path.HasExtension(url))
{
url = url + Constants.DefaultExtension;
}
if (!url.StartsWith("/"))
{
url = "/" + url;
}
return url;
}
protected virtual string GetPageContent(string url, Localization localization)
{
string cmUrl = GetCmUrl(url);
using (new Tracer(url, cmUrl))
{
IPageFactory pageFactory = DD4TFactoryCache.GetPageFactory(localization);
string result;
pageFactory.TryFindPageContent(GetCmUrl(url), out result);
return result;
}
}
protected virtual IPage GetPage(string url, Localization localization)
{
string cmUrl = GetCmUrl(url);
using (new Tracer(url, cmUrl))
{
IPageFactory pageFactory = DD4TFactoryCache.GetPageFactory(localization);
IPage result;
pageFactory.TryFindPage(cmUrl, out result);
return result;
}
}
protected virtual int MapSchema(string schemaKey, Localization localization)
{
string[] schemaKeyParts = schemaKey.Split('.');
string moduleName = schemaKeyParts.Length > 1 ? schemaKeyParts[0] : SiteConfiguration.CoreModuleName;
schemaKey = schemaKeyParts.Length > 1 ? schemaKeyParts[1] : schemaKeyParts[0];
string schemaId = localization.GetConfigValue(string.Format("{0}.schemas.{1}", moduleName, schemaKey));
int result;
Int32.TryParse(schemaId, out result);
return result;
}
protected virtual IEnumerable<IPage> GetIncludesFromModel(IPage page, Localization localization)
{
List<IPage> result = new List<IPage>();
string[] pageTemplateTcmUriParts = page.PageTemplate.Id.Split('-');
IEnumerable<string> includePageUrls = SiteConfiguration.GetIncludePageUrls(pageTemplateTcmUriParts[1], localization);
foreach (string includePageUrl in includePageUrls)
{
IPage includePage = GetPage(SiteConfiguration.LocalizeUrl(includePageUrl, localization), localization);
if (includePage == null)
{
Log.Error("Include Page '{0}' not found.", includePageUrl);
continue;
}
FullyLoadDynamicComponentPresentations(includePage, localization);
result.Add(includePage);
}
return result;
}
/// <summary>
/// Ensures that the Component Fields of DCPs on the Page are populated.
/// </summary>
private static void FullyLoadDynamicComponentPresentations(IPage page, Localization localization)
{
using (new Tracer(page, localization))
{
foreach (ComponentPresentation dcp in page.ComponentPresentations.Where(cp => cp.IsDynamic).OfType<ComponentPresentation>())
{
IComponentFactory componentFactory = DD4TFactoryCache.GetComponentFactory(localization);
dcp.Component = (Component)componentFactory.GetComponent(dcp.Component.Id, dcp.ComponentTemplate.Id);
}
}
}
}
}