import { BASE_URL, WEBSUB_HUB } from '$env/static/private'; import { PUBLIC_MASTODON_INSTANCE_DISPLAY_NAME } from '$env/static/public'; import type { Post } from '$lib//mastodon/response'; import { Logger } from '$lib/log'; import { Feed } from 'feed'; import fs from 'fs/promises'; const { PROD } = import.meta.env; const logger = new Logger('RSS'); export function createFeed(posts: Post[]): Feed { const baseUrl = BASE_URL.endsWith('/') ? BASE_URL : BASE_URL + '/'; const hub = WEBSUB_HUB ? WEBSUB_HUB : undefined; const feed = new Feed({ title: `${PUBLIC_MASTODON_INSTANCE_DISPLAY_NAME} music feed`, description: `Posts about music on ${PUBLIC_MASTODON_INSTANCE_DISPLAY_NAME}`, id: baseUrl, link: baseUrl, language: 'en', //image: "http://example.com/image.png", //favicon: "http://example.com/favicon.ico", copyright: '', generator: 'moshing-mamut', feedLinks: { atom: `${BASE_URL}/feed.xml` }, hub: hub, author: { name: '@aymm', link: 'https://metalhead.club/@aymm' } }); posts.forEach((p) => { feed.addItem({ title: p.content, id: p.url, link: p.url, content: p.content, author: [ { name: p.account.acct, link: p.account.url } ], date: new Date(p.created_at) }); }); feed.addCategory('Music'); return feed; } export async function saveAtomFeed(feed: Feed) { await fs.writeFile('feed.xml', feed.atom1(), { encoding: 'utf8' }); if (!WEBSUB_HUB || !PROD) { logger.info('Skipping Websub publish. hub configured?', WEBSUB_HUB, 'Production?', PROD); return; } try { const param = new FormData(); param.append('hub.mode', 'publish'); param.append('hub.url', `${BASE_URL}/feed.xml`); await fetch(WEBSUB_HUB, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: param }); } catch (e) { logger.error('Failed to update WebSub hub', e); } }