Files
Umbraco-CMS/src/Umbraco.Core/Routing/DefaultMediaUrlProvider.cs

76 lines
2.5 KiB
C#
Raw Normal View History

2019-04-15 15:57:35 +02:00
using System;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
2019-04-15 15:57:35 +02:00
namespace Umbraco.Web.Routing
{
/// <summary>
2020-10-05 20:48:38 +02:00
/// Default media URL provider.
2019-04-15 15:57:35 +02:00
/// </summary>
public class DefaultMediaUrlProvider : IMediaUrlProvider
{
private readonly UriUtility _uriUtility;
private readonly MediaUrlGeneratorCollection _mediaPathGenerators;
public DefaultMediaUrlProvider(MediaUrlGeneratorCollection mediaPathGenerators, UriUtility uriUtility)
{
_mediaPathGenerators = mediaPathGenerators ?? throw new ArgumentNullException(nameof(mediaPathGenerators));
_uriUtility = uriUtility;
}
2019-04-15 15:57:35 +02:00
/// <inheritdoc />
public virtual UrlInfo GetMediaUrl(IPublishedContent content,
string propertyAlias, UrlMode mode, string culture, Uri current)
2019-04-15 15:57:35 +02:00
{
var prop = content.GetProperty(propertyAlias);
// get the raw source value since this is what is used by IDataEditorWithMediaPath for processing
var value = prop?.GetSourceValue(culture);
2019-04-15 15:57:35 +02:00
if (value == null)
{
return null;
}
2019-04-23 16:23:06 +02:00
var propType = prop.PropertyType;
2019-04-15 15:57:35 +02:00
if (_mediaPathGenerators.TryGetMediaPath(propType.EditorAlias, value, out var path))
2019-04-15 15:57:35 +02:00
{
var url = AssembleUrl(path, current, mode);
return UrlInfo.Url(url.ToString(), culture);
2019-04-15 15:57:35 +02:00
}
return null;
2019-04-15 15:57:35 +02:00
}
2019-04-24 09:32:49 +02:00
private Uri AssembleUrl(string path, Uri current, UrlMode mode)
2019-04-15 15:57:35 +02:00
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException($"{nameof(path)} cannot be null or whitespace", nameof(path));
2019-04-15 15:57:35 +02:00
// the stored path is absolute so we just return it as is
if (Uri.IsWellFormedUriString(path, UriKind.Absolute))
return new Uri(path);
2019-04-15 15:57:35 +02:00
Uri uri;
if (current == null)
2019-04-24 09:32:49 +02:00
mode = UrlMode.Relative; // best we can do
2019-04-15 15:57:35 +02:00
switch (mode)
{
2019-04-24 09:32:49 +02:00
case UrlMode.Absolute:
2019-04-15 15:57:35 +02:00
uri = new Uri(current?.GetLeftPart(UriPartial.Authority) + path);
break;
2019-04-24 09:32:49 +02:00
case UrlMode.Relative:
case UrlMode.Auto:
2019-04-15 15:57:35 +02:00
uri = new Uri(path, UriKind.Relative);
break;
default:
throw new ArgumentOutOfRangeException(nameof(mode));
}
return _uriUtility.MediaUriFromUmbraco(uri);
2019-04-15 15:57:35 +02:00
}
}
}