Add Atom feed

This commit is contained in:
Laura Hausmann 2022-11-26 15:51:29 +01:00
parent b44a4762d1
commit 105b2069f4
Signed by: zotan
GPG key ID: D044E84C5BE01605
3 changed files with 54 additions and 1 deletions

View file

@ -1,4 +1,7 @@
using System.Reflection;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
namespace zotanpw.Backend;
@ -21,4 +24,18 @@ public static class Utils {
_ => "a"
};
}
}
public static string ToXmlString(this SyndicationFeedFormatter feed) {
using var sw = new StringWriterWithEncoding(Encoding.UTF8);
using (var xw = XmlWriter.Create(sw, new XmlWriterSettings { Encoding = Encoding.UTF8 }))
feed.WriteTo(xw);
return sw.ToString();
}
private sealed class StringWriterWithEncoding : StringWriter {
public StringWriterWithEncoding(Encoding encoding) => Encoding = encoding;
public override Encoding Encoding { get; }
}
}

35
Controllers/AtomFeed.cs Normal file
View file

@ -0,0 +1,35 @@
using System.ServiceModel.Syndication;
using Microsoft.AspNetCore.Mvc;
using zotanpw.Backend;
using zotanpw.Pages.blog;
namespace zotanpw.Controllers;
[ApiController]
public class AtomFeed : Controller {
private static readonly string AtomXml;
static AtomFeed() {
var feed = new SyndicationFeed {
Id = "https://zotan.pw/blog",
Title = new TextSyndicationContent("zotan.pw >> blog"),
Description = new TextSyndicationContent("Blog of a disabled neurodivergent queer person unhappy with the state of the world"),
LastUpdatedTime = DateTimeOffset.Now,
Authors = { new SyndicationPerson("zotan@zotan.pw", "zotan", "https://zotan.pw") },
Items = BlogModel.Posts.Take(10)
.Select(post => new SyndicationItem(post.Title, new TextSyndicationContent(post.Content, TextSyndicationContentKind.Html),
new Uri($"https://zotan.pw/blog/{post.Shorthand}"), $"https://zotan.pw/blog/{post.Shorthand}",
post.PublishedOn.ToDateTime(TimeOnly.MinValue)))
.ToList(),
Links = { SyndicationLink.CreateSelfLink(new Uri("https://zotan.pw/blog/feed.atom")) }
};
AtomXml = new Atom10FeedFormatter(feed).ToXmlString();
}
[HttpGet, Route("/blog/feed.atom")]
public ActionResult GetAtomFeed() {
Response.ContentType = "application/atom+xml";
return Content(AtomXml);
}
}

View file

@ -13,6 +13,7 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="7.0.0"/>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.0"/>
<PackageReference Include="System.Data.SQLite" Version="1.0.115"/>
<PackageReference Include="System.ServiceModel.Syndication" Version="7.0.0"/>
<PackageReference Include="YamlDotNet" Version="12.0.2"/>
</ItemGroup>