-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSitemap.cs
79 lines (66 loc) · 2.45 KB
/
Sitemap.cs
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
using System.Xml.Linq;
using SharedModels;
namespace SitemapGenerator;
public class Sitemap(TableOfContents tableOfContents, string channel)
{
private XDocument? _sitemap;
private readonly List<Url> _urls =
channel.Equals("Channel")
? [.. tableOfContents.AvailableContentTypes.Select(contentType => new Url
{
Loc = $"https://ilovedotnet.org/channels/{contentType.ToLower().Replace(" ", "-")}",
LastMod = tableOfContents.GetContentsByChannel(contentType)[0].ModifiedOn,
ChangeFreq = "weekly",
Priority = 0.5
})]
: [.. tableOfContents.GetContentsByChannel(channel).Select(content => new Url
{
Loc = $"https://ilovedotnet.org/blogs/{content.Slug}",
LastMod = new DateTime(content.ModifiedOn.Year, content.ModifiedOn.Month, content.ModifiedOn.Day, content.ModifiedOn.Hour, content.ModifiedOn.Minute, content.ModifiedOn.Second),
ChangeFreq = "weekly",
Priority = 0.5
})];
public void GenerateSitemap(string filePath)
{
LoadSitemap(filePath);
if (!IsAnyContentUpdatedAndRepublished() && !isAnyNewContentAddedOrScheduled)
{
return;
}
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XElement urlset = new(ns + "urlset");
foreach (var url in _urls)
{
XElement urlElement = new(ns + "url",
new XElement(ns + "loc", url.Loc),
new XElement(ns + "lastmod", url.LastMod.ToString("yyyy-MM-ddTHH:mm:sszzz")),
new XElement(ns + "changefreq", url.ChangeFreq),
new XElement(ns + "priority", url.Priority)
);
urlset.Add(urlElement);
}
XDocument sitemap = new(new XDeclaration("1.0", "UTF-8", "yes"), urlset);
sitemap.Save(filePath);
}
private void LoadSitemap(string filePath)
{
if (File.Exists(filePath))
{
_sitemap = XDocument.Load(filePath);
}
}
private bool IsAnyContentUpdatedAndRepublished()
{
if (_sitemap is null)
{
return false;
}
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
var isAnyContentUpdatedAndRepublished = _urls.Any(url =>
_sitemap.Descendants(ns + "url").Any(existingUrl =>
existingUrl.Element(ns + "loc")?.Value == url.Loc &&
existingUrl.Element(ns + "lastmod")?.Value != url.LastMod.ToString("yyyy-MM-ddTHH:mm:sszzz")));
return isAnyContentUpdatedAndRepublished;
}
private bool isAnyNewContentAddedOrScheduled => _urls.Count != _sitemap?.Descendants("url").Count();
}