web/src/pages/rss.xml.ts

226 lines · 6626 bytes

13 symbols in this file
  1import rss from '@astrojs/rss';
  2import type { APIContext } from 'astro';
  3import { fetchChangelog, type ChangelogEntry } from '../utils/fetch-changelog';
  4import { slugify } from '../utils/fetch-data';
  5
  6const MAX_ITEMS = 50;
  7const FALLBACK_SITE = 'https://awesome-privacy.xyz';
  8
  9const escapeHtml = (s: string) =>
 10  s.replace(
 11    /[&<>"']/g,
 12    (c) =>
 13      ({
 14        '&': '&amp;',
 15        '<': '&lt;',
 16        '>': '&gt;',
 17        '"': '&quot;',
 18        "'": '&#39;',
 19      })[c] as string,
 20  );
 21
 22const pl = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
 23
 24const serviceUrl = (
 25  site: URL,
 26  c: { category: string; section: string; name: string },
 27) =>
 28  new URL(
 29    `/${slugify(c.category)}/${slugify(c.section)}/${slugify(c.name)}`,
 30    site,
 31  ).toString();
 32
 33const sectionUrl = (site: URL, s: { category: string; name: string }) =>
 34  new URL(`/${slugify(s.category)}/${slugify(s.name)}`, site).toString();
 35
 36const categoryUrl = (site: URL, name: string) =>
 37  new URL(`/${slugify(name)}`, site).toString();
 38
 39const hasAnyChange = (e: ChangelogEntry): boolean => {
 40  const { services: s, sections: sc, categories: ct } = e.changes ?? {};
 41  return Boolean(
 42    s?.added?.length ||
 43    s?.removed?.length ||
 44    s?.modified?.length ||
 45    s?.moved?.length ||
 46    s?.renamed?.length ||
 47    sc?.added?.length ||
 48    sc?.removed?.length ||
 49    sc?.moved?.length ||
 50    ct?.added?.length ||
 51    ct?.removed?.length,
 52  );
 53};
 54
 55const summaryParts = (e: ChangelogEntry): string[] => {
 56  const { services: s, sections: sc, categories: ct } = e.changes ?? {};
 57  const parts: string[] = [];
 58  if (s?.added?.length) parts.push(pl(s.added.length, 'addition'));
 59  if (s?.removed?.length) parts.push(pl(s.removed.length, 'removal'));
 60  if (s?.modified?.length) parts.push(pl(s.modified.length, 'update'));
 61  if (s?.renamed?.length) parts.push(pl(s.renamed.length, 'rename'));
 62  if (s?.moved?.length) parts.push(pl(s.moved.length, 'move'));
 63  if (sc?.added?.length) parts.push(pl(sc.added.length, 'new section'));
 64  if (sc?.removed?.length) parts.push(pl(sc.removed.length, 'removed section'));
 65  if (sc?.moved?.length) parts.push(pl(sc.moved.length, 'moved section'));
 66  if (ct?.added?.length) parts.push(pl(ct.added.length, 'new category'));
 67  if (ct?.removed?.length)
 68    parts.push(pl(ct.removed.length, 'removed category'));
 69  return parts;
 70};
 71
 72const buildContent = (e: ChangelogEntry, site: URL): string => {
 73  const { services: s, sections: sc, categories: ct } = e.changes ?? {};
 74  const blocks: string[] = [];
 75  const list = (title: string, inner: string) =>
 76    blocks.push(`<h3>${title}</h3><ul>${inner}</ul>`);
 77  const li = (html: string) => `<li>${html}</li>`;
 78
 79  if (s?.added?.length)
 80    list(
 81      'Added',
 82      s.added
 83        .map((i) =>
 84          li(
 85            `<a href="${serviceUrl(site, i)}">${escapeHtml(i.name)}</a> — ${escapeHtml(i.category)} / ${escapeHtml(i.section)}`,
 86          ),
 87        )
 88        .join(''),
 89    );
 90  if (s?.removed?.length)
 91    list(
 92      'Removed',
 93      s.removed
 94        .map((i) =>
 95          li(
 96            `${escapeHtml(i.name)} — ${escapeHtml(i.category)} / ${escapeHtml(i.section)}`,
 97          ),
 98        )
 99        .join(''),
100    );
101  if (s?.modified?.length)
102    list(
103      'Updated',
104      s.modified
105        .map((i) =>
106          li(
107            `<a href="${serviceUrl(site, i)}">${escapeHtml(i.name)}</a>${
108              i.fields?.length ? ` (${escapeHtml(i.fields.join(', '))})` : ''
109            }`,
110          ),
111        )
112        .join(''),
113    );
114  if (s?.renamed?.length)
115    list(
116      'Renamed',
117      s.renamed
118        .map((i) =>
119          li(
120            `${escapeHtml(i.previousName)} → <a href="${serviceUrl(site, { ...i.to, name: i.name })}">${escapeHtml(i.name)}</a>`,
121          ),
122        )
123        .join(''),
124    );
125  if (s?.moved?.length)
126    list(
127      'Moved',
128      s.moved
129        .map((i) =>
130          li(
131            `<a href="${serviceUrl(site, { ...i.to, name: i.name })}">${escapeHtml(i.name)}</a>: ${escapeHtml(i.from.category)}/${escapeHtml(i.from.section)} → ${escapeHtml(i.to.category)}/${escapeHtml(i.to.section)}`,
132          ),
133        )
134        .join(''),
135    );
136  if (sc?.added?.length)
137    list(
138      'New sections',
139      sc.added
140        .map((i) =>
141          li(
142            `<a href="${sectionUrl(site, i)}">${escapeHtml(i.name)}</a> in ${escapeHtml(i.category)}`,
143          ),
144        )
145        .join(''),
146    );
147  if (sc?.removed?.length)
148    list(
149      'Removed sections',
150      sc.removed
151        .map((i) => li(`${escapeHtml(i.name)} (${escapeHtml(i.category)})`))
152        .join(''),
153    );
154  if (ct?.added?.length)
155    list(
156      'New categories',
157      ct.added
158        .map((i) =>
159          li(`<a href="${categoryUrl(site, i)}">${escapeHtml(i)}</a>`),
160        )
161        .join(''),
162    );
163  if (ct?.removed?.length)
164    list(
165      'Removed categories',
166      ct.removed.map((i) => li(escapeHtml(i))).join(''),
167    );
168
169  if (e.pr) {
170    const author = e.pr.author
171      ? ` by <a href="https://github.com/${escapeHtml(e.pr.author)}">@${escapeHtml(e.pr.author)}</a>`
172      : '';
173    blocks.push(
174      `<p>Contributed via <a href="${e.pr.url}">PR #${e.pr.number}</a>${author}.</p>`,
175    );
176  }
177
178  return blocks.join('');
179};
180
181const itemLink = (e: ChangelogEntry, site: URL): string => {
182  if (e.pr?.url) return e.pr.url;
183  const anchor = e.sha || e.date;
184  return new URL(`/changelog#${encodeURIComponent(anchor)}`, site).toString();
185};
186
187const formatDateGb = (iso: string) =>
188  new Date(iso).toLocaleDateString('en-GB', {
189    day: 'numeric',
190    month: 'short',
191    year: 'numeric',
192  });
193
194export async function GET(context: APIContext) {
195  const site = new URL(context.site?.toString() || FALLBACK_SITE);
196  const { entries } = await fetchChangelog();
197
198  const items = entries
199    .filter(hasAnyChange)
200    .slice()
201    .sort((a, b) => (a.date < b.date ? 1 : -1))
202    .slice(0, MAX_ITEMS)
203    .map((e) => {
204      const parts = summaryParts(e);
205      const summary = parts.join(', ');
206      return {
207        title: `${formatDateGb(e.date)} — ${summary || 'Update'}`,
208        link: itemLink(e, site),
209        pubDate: new Date(e.date),
210        description: summary,
211        content: buildContent(e, site),
212      };
213    });
214
215  return rss({
216    title: 'Awesome Privacy - Changelog',
217    description:
218      'Latest additions, removals and updates to the directory of privacy-respecting software and services.',
219    site: site.toString(),
220    items,
221    customData:
222      '<language>en-gb</language>' +
223      `<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>`,
224    trailingSlash: false,
225  });
226}