Files
mixtape/Finch/Metadata/MetadataService.cs
T

80 lines
2.0 KiB
C#
Raw Normal View History

using System.Reflection;
2024-03-15 00:35:32 +01:00
using System.Text;
using Microsoft.Extensions.Hosting;
2024-02-06 16:00:44 +01:00
2026-04-07 14:23:29 +02:00
namespace Finch.Metadata;
2024-02-06 16:00:44 +01:00
public class MetadataService(ILocalizer localizer, IHostEnvironment env) : IMetadataService
2024-02-06 16:00:44 +01:00
{
/// <inheritdoc />
2024-03-15 00:35:32 +01:00
public virtual Metadata Generate(string pageName, MetadataOptions options)
2024-02-06 16:00:44 +01:00
{
Metadata model = new()
{
Description = options.Description,
Icon = options.Icon,
Image = options.Image,
Author = options.Author,
PageName = pageName,
2025-08-25 13:45:05 +02:00
AppVersion = Assembly.GetEntryAssembly()!.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+').FirstOrDefault()};
2024-02-06 16:00:44 +01:00
// generate robots
bool noIndex = options.NoIndex ?? false;
bool noFollow = options.NoFollow ?? false;
// noindex+nofollow when not in production
if (!env.IsProduction())
{
noIndex = true;
noFollow = true;
}
model.Robots = $"{(noIndex ? "noindex" : "index")},{(noFollow ? "nofollow" : "follow")}";
2024-02-06 16:00:44 +01:00
// title
HashSet<string> fragments = options.TitleFragments.Where(x => !x.IsNullOrWhiteSpace()).Reverse().ToHashSet();
2024-03-15 00:35:32 +01:00
model.Title = GenerateTitle(pageName, fragments, options);
2024-02-06 16:00:44 +01:00
// add schema
//if (options.Schema != null)
//{
// model.Schema = options.Schema.ToJson();
//}
return model;
}
2024-03-15 00:35:32 +01:00
/// <summary>
/// Generates the page title based on passed fragments
/// </summary>
protected virtual string GenerateTitle(string pageName, HashSet<string> fragments, MetadataOptions options)
{
StringBuilder sb = new();
if (fragments.Count != 0)
{
sb.Append(string.Join(options.TitleFragmentsSeparator, fragments.Select(localizer.Maybe)));
2024-03-15 00:35:32 +01:00
if (!options.HidePageName)
{
sb.Append(options.TitlePageNameToFragmentSeparator);
sb.Append(pageName);
}
}
else
{
sb.Append(pageName);
}
return sb.ToString();
}
2024-02-06 16:00:44 +01:00
}
public interface IMetadataService
{
/// <summary>
/// Generates metadata.
/// </summary>
Metadata Generate(string pageName, MetadataOptions options);
}