Skip to content

Instantly share code, notes, and snippets.

@aDotNetDeveloper
Created February 11, 2018 22:16
Show Gist options
  • Save aDotNetDeveloper/0e05801311a3e7fcecdf910638f66fa4 to your computer and use it in GitHub Desktop.
Save aDotNetDeveloper/0e05801311a3e7fcecdf910638f66fa4 to your computer and use it in GitHub Desktop.
Latest bits from Umbraco micro service repository
using System.Web.Mvc;
using System.Linq;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Web.Mvc;
using Inferno.Services.ContentModels;
using Inferno.Services.MediaCMS.Repository;
using System.Net.Http.Formatting;
using System;
namespace Inferno.Services.MediaCMS.Controllers
{
public abstract class DefaultPageController<T> : RenderMvcController where T : class
{
protected Func<IPublishedContent, T, T> ProcessingCallback;
private INavigationRepository _NavigationRepository;
public DefaultPageController(INavigationRepository NavigationRepository)
{
_NavigationRepository = NavigationRepository;
ProcessingCallback += ProcessNavigation;
}
public T ExecutePostProcessing(IPublishedContent publishedContent, T param, Func<IPublishedContent, T, T> x) => x != null ? x(publishedContent, param) : param;
protected ActionResult Index(IPublishedContent model) => RenderAsJson(model);
protected ViewResult View(IPublishedContent model) => base.View(ContentModel.As<T>(model));
protected virtual ActionResult RenderAsJson(IPublishedContent model)
{
var content = ContentModel.As<T>(model);
content = ExecutePostProcessing(model, content, ProcessingCallback);
JsonMediaTypeFormatter formatter = (JsonMediaTypeFormatter)System.Web.Http.GlobalConfiguration.Configuration.Formatters.Where(f => f is JsonMediaTypeFormatter && f.SupportedMediaTypes.Any(t => t.MediaType.Equals(Request.ContentType))).FirstOrDefault();
var serializerSettings = formatter?.SerializerSettings ?? System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(content, serializerSettings), "application/json");
}
private T ProcessNavigation(IPublishedContent model, T content)
{
INavigatable navigatable = content is INavigatable ? (INavigatable)content : null;
if (navigatable != null)
{
navigatable.Navigation = _NavigationRepository?.CreateNavigation(model);
}
return content;
}
}
}
using Inferno.Services.ContentModels.Processors;
using Newtonsoft.Json;
using Our.Umbraco.Ditto;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System;
using Inferno.Services.ContentModels.Extensions;
namespace Inferno.Services.ContentModels
{
[UmbracoPicker]
public abstract class MediaItem : IMediaItem, IMediaImageSet, IComponent
{
protected Image _shelfImage;
protected Image _backgroundImage;
protected Image _backgroundImageNoLogo;
protected Image _backgroundImageIPTV;
protected Image _bannerImage;
protected virtual Image GetImageWithAltTag(Image image, Image defaultImage = null)
{
image = image ?? defaultImage?.Clone(imageFallback: true);
if (image != null) image.AltTag = Title;
return image;
}
[ScriptIgnore]
[JsonIgnore]
public int Id { get; set; }
[ContentDataProcessor(IncludeUrl: true)]
[JsonProperty(Order = 0)]
public ComponentData ComponentData { get; set; }
[JsonProperty(Order = 1)]
[UmbracoProperty(AltPropertyName = "ibmsTitle")]
public string Title { get; set; }
[UmbracoAncestorProperty(propertyName: "longSynopsis", altPropertyName: "ibmsLongSynopsis", recursive: true)]
public string LongSynopsis { get; set; }
[UmbracoAncestorProperty(propertyName: "shortSynopsis", altPropertyName: "ibmsShortSynopsis", recursive: true)]
public string ShortSynopsis { get; set; }
[UmbracoAncestorProperty(propertyName: "extraShortSynopsis", altPropertyName: "shortSynopsis", recursive: true)]
public string ExtraShortSynopsis { get; set; }
[UmbracoProperty(Recursive = true)]
public bool Featured { get; set; }
// Images
[UmbracoProperty(Recursive = true)]
public Image ShelfImage
{
get { return GetImageWithAltTag(_shelfImage, defaultImage: BackgroundImageLogo); }
set { _shelfImage = value; }
}
[UmbracoProperty(propertyName: "backgroundImageLogo", Recursive = true)]
public Image BackgroundImageLogo
{
get { return GetImageWithAltTag(_backgroundImage, defaultImage: null); }
set { _backgroundImage = value; }
}
[UmbracoProperty(propertyName: "backgroundImage", Recursive = true)]
public Image BackgroundImage
{
get { return GetImageWithAltTag(_backgroundImageNoLogo, defaultImage: BackgroundImageLogo); }
set { _backgroundImageNoLogo = value; }
}
[UmbracoProperty(propertyName: "backgroundImageIPTV", Recursive = true)]
public Image BackgroundImageIPTV
{
get { return GetImageWithAltTag(_backgroundImageIPTV, defaultImage: BackgroundImage); }
set { _backgroundImageIPTV = value; }
}
[UmbracoProperty(Recursive = true)]
public Image BannerImage
{
get { return GetImageWithAltTag(_bannerImage, defaultImage: BackgroundImageLogo); }
set { _bannerImage = value; }
}
// Classification
[UmbracoProperty(AltPropertyName = "ibmsClassification")]
public string Classification { get; set; }
[UmbracoProperty(AltPropertyName = "ibmsTags")]
public string Tags { get; set; }
[UmbracoAncestorProperty(propertyName: "genre", altPropertyName: "ibmsGenre", recursive: true)] // Ancestor genre, if no value ibmsGenre alt property, recursively up the node tree in this property order
public IEnumerable<string> Genre { get; set; }
[UmbracoProperty(AltPropertyName = "ibmsSubGenre", Recursive = true)]
public IEnumerable<string> SubGenre { get; set; }
[UmbracoProperty(PropertyName = "ibmsChannel", Recursive = true)]
public string Channel { get; set; }
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty("premiereDate", Recursive = true)]
public DateTime ReleaseDate { get; set; }
public string PremiereDate { get => DateTime.MinValue.Equals(ReleaseDate) ? null : ReleaseDate.ToString("o"); }
// Cast
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty(AltPropertyName = "ibmsLeadActors")]
public string LeadActors { get; set; }
[JsonProperty("LeadActors")]
public string CastLeadActors => LeadActors.MultilineValueToCsv();
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty(AltPropertyName = "ibmsActors")]
public string Actors { get; set; }
[JsonProperty("Actors")]
public string CastActors => Actors.MultilineValueToCsv();
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty(AltPropertyName = "ibmsGuestStars")]
public string GuestStars { get; set; }
[JsonProperty("GuestStars")]
public string CastGuestStars => GuestStars.MultilineValueToCsv();
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty(AltPropertyName = "ibmsDirectors")]
public string Directors { get; set; }
[JsonProperty("Directors")]
public string CastDirectors => Directors.MultilineValueToCsv();
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty(AltPropertyName = "ibmsWriters")]
public string Writers { get; set; }
[JsonProperty("Writers")]
public string CastWriters => Writers.MultilineValueToCsv();
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty(AltPropertyName = "ibmsCreators")]
public string Creators { get; set; }
[JsonProperty("creators")]
public string CastCreators => Creators.MultilineValueToCsv();
[ScriptIgnore]
[JsonIgnore]
[UmbracoProperty("updateDate")]
public DateTime ModifiedDate { get; set; }
public string UpdateDate { get => DateTime.MinValue.Equals(ModifiedDate) ? null : ModifiedDate.ToUniversalTime().ToString("o"); }
}
}
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Models;
using Umbraco.Web;
using System.Text.RegularExpressions;
using Inferno.Services.ContentModels;
using Processors = Inferno.Services.ContentModels.Processors;
using Inferno.Services.ContentModels.Extensions;
namespace Inferno.Services.MediaCMS.Repository
{
public class NavigationRepository : INavigationRepository
{
private UmbracoContext _umbracoContext;
private UmbracoHelper _umbracoHelper;
private static string[] NonPageTypes = Processors.PublishedContentExtensions.ComponentTypes;
public NavigationRepository(UmbracoContext umbracoContext)
{
_umbracoContext = umbracoContext;
_umbracoHelper = new UmbracoHelper(umbracoContext);
}
internal Navigation CreateNavigation(IPublishedContent node)
{
var root = Root<HomePage>(node);
return new Navigation
{
SiteLogo = root.SiteLogo,
// if this is a root node, force the first homepage to be the navigation source
Items = ChildrenFromRoot(node)
};
}
public IPublishedContent Root(IPublishedContent node)
{
return _umbracoHelper.TypedContentAtRoot().Where(n => n.DocumentTypeAlias.Equals(HomePage.ModelTypeAlias) && (node == null || (n.Id == node.AncestorOrSelf(1).Id))).FirstOrDefault();
}
public T Root<T>(IPublishedContent node) where T : Page
{
return ContentModel.As<T>(Root(node));
}
public IEnumerable<NavigationItem> ChildrenFromRoot(IPublishedContent page, bool includeComponents = false)
{
var root = Root(page);
return (from node in root.Descendants().Where(n => n.IsVisible() && (includeComponents || !NonPageTypes.Contains(n.DocumentTypeAlias)))
let id = node.HasValue("umbracoRedirect") ? node.GetPropertyValue<int>("umbracoRedirect") : node.Id
select CreateNavigationItem(node, id == page.Id));
}
private IEnumerable<NavigationItem> Children(IPublishedContent page, bool includeComponents = false)
{
return (from node in page.Children.Where(n => n.IsVisible() && (includeComponents || !NonPageTypes.Contains(n.DocumentTypeAlias)))
let id = node.HasValue("umbracoRedirect") ? node.GetPropertyValue<int>("umbracoRedirect") : node.Id
select CreateNavigationItem(node, id == page.Id));
}
private NavigationItem CreateNavigationItem(IPublishedContent node, bool active = false)
{
var title = node.Title.AsNiceTitle();
var name = node.Name.AsNiceTitle();
return new NavigationItem
{
Id = node.Id.ToString(),
ComponentType = node.DocumentTypeAlias,
Visible = !NonPageTypes.Contains(node.DocumentTypeAlias),
Active = active,
Title = string.IsNullOrWhiteSpace(title) ? name : title,
Name = name,
Items = active ? Children(node) : null,
Url = node.Url
};
}
}
}
using Inferno.Services.ContentModels;
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Web;
using Umbraco.Core.Cache;
using Umbraco.Web.Routing;
using Umbraco.Core.Models;
namespace Inferno.Services.MediaCMS.Providers
{
public class VideoLibraryUrlProvider : BaseUrlProvider, IUrlProvider
{
public static string CacheName = "VideoLibraryUrlProvider";
public static double CacheTimeout = 3600;
private readonly string[] types;
public VideoLibraryUrlProvider()
{
types = ContentModels.Processors.PublishedContentExtensions.VideoLibraryTypes;
}
public IPublishedContent rootNode { get; private set; }
internal static IPublishedContent GetVideoLibraryRoot(UmbracoContext umbracoContext)
{
return umbracoContext.Application.ApplicationCache.RuntimeCache.GetCacheItem<IPublishedContent>(VideoLibraryUrlProvider.CacheName, () => umbracoContext.ContentCache.GetAtRoot(false).Where(n => n.DocumentTypeAlias.Equals(MediaLibrary.ModelTypeAlias))?.FirstOrDefault(), TimeSpan.FromSeconds(CacheTimeout));
}
public static void ClearCache(UmbracoContext umbracoContext, int id)
{
umbracoContext.Application.ApplicationCache.RuntimeCache.ClearCacheItem(VideoLibraryUrlProvider.CacheName);
umbracoContext.Application.ApplicationCache.RuntimeCache.ClearCacheItem($"{VideoLibraryUrlProvider.CacheName}-url-{id}");
umbracoContext.Application.ApplicationCache.RuntimeCache.ClearCacheItem($"{VideoLibraryUrlProvider.CacheName}-otherurl-{id}");
}
public IEnumerable<string> GetOtherUrls(UmbracoContext umbracoContext, int id, Uri current)
{
if (!current.IsAbsoluteUri)
throw new ArgumentException("Current url must be absolute.", "current");
return umbracoContext.Application.ApplicationCache.RuntimeCache.GetCacheItem<IEnumerable<string>>($"{VideoLibraryUrlProvider.CacheName}-otherurl-{id}",
() =>
{
var content = umbracoContext.ContentCache.GetById(id);
return GetSecondaryUrls(umbracoContext, content, current);
}, TimeSpan.FromSeconds(CacheTimeout));
}
internal IEnumerable<string> GetSecondaryUrls(UmbracoContext umbracoContext, IPublishedContent content, Uri current)
{
if (content != null && types.Contains(content.DocumentTypeAlias) && content.HasProperty("broadcasterReference"))
{
rootNode = GetVideoLibraryRoot(umbracoContext);
var broadcasterReference = content.GetPropertyValue<string>("broadcasterReference");
if (string.IsNullOrEmpty(broadcasterReference)) return Enumerable.Empty<string>();
// Build path
string route = $"/{rootNode?.UrlName}/{broadcasterReference}/";
// Setup domain uri
var domainUri = new Uri(current.GetLeftPart(UriPartial.Authority));
return new[] { AssembleUrl(domainUri, route, current, UrlProviderMode.Auto).ToString() };
}
return Enumerable.Empty<string>();
}
public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode)
{
if (!current.IsAbsoluteUri)
throw new ArgumentException("Current url must be absolute.", "current");
return umbracoContext.Application.ApplicationCache.RuntimeCache.GetCacheItem<string>($"{VideoLibraryUrlProvider.CacheName}-url-{id}",
() =>
{
var r = umbracoContext.ContentCache.GetRouteById(id);
var content = umbracoContext.ContentCache.GetById(id);
if (content != null && types.Contains(content.DocumentTypeAlias))
{
rootNode = GetVideoLibraryRoot(umbracoContext);
// Build path
string route = $"/{rootNode?.UrlName}{r}/";
// Setup domain uri
var domainUri = new Uri(current.GetLeftPart(UriPartial.Authority));
return AssembleUrl(domainUri, route, current, mode).ToString();
}
return r;
}, TimeSpan.FromSeconds(CacheTimeout));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment