import Api, { FetchError } from '~api' import links from '~config/links' const escapeXml = s => String(s ?? '').replace(/&/g, '&').replace(//g, '>') const escapeAttr = s => escapeXml(s).replace(/"/g, '"') const collectionUrl = (author, collection) => `https://${author.name}.${links.pub.domain}/${collection.slug}-${collection._id}` function renderItem(item) { const body = item.note || item.excerpt || '' const html = (item.cover && item.cover != '' ? `
` : '') + body return ` ${escapeXml(item.title)} ${escapeXml(item.link)} ${escapeXml(html)} ${new Date(item.created).toUTCString()} ${escapeXml(item.link)} ${item.tags?.map(tag => `${escapeXml(tag)}`).join('')} ` } function renderFeed({ collection, items, author }) { const cover = Array.isArray(collection.cover) ? collection.cover[0] : '' const channelLink = collectionUrl(author, collection) const selfHref = `${channelLink}/feed` return ` ${escapeXml(collection.title)} ${escapeXml(channelLink)} ${escapeXml(collection.description)} en-US raindrop.io ${cover ? ` ${escapeXml(cover)} ${escapeXml(channelLink)} ${escapeXml(collection.title)} ` : ''} ${items.length ? `${new Date(items[0].lastUpdate).toUTCString()}` : ''} ${items.map(renderItem).join('')} ` } export default async function handleFeed(c) { const id = Number(c.req.param('slug_id')?.split('-').at(-1)) if (!id) return c.text('', 404) let collection, raindrops try { collection = await Api.collection.get(id, { signal: c.req.raw.signal }) raindrops = await Api.raindrops.get(id, { perpage: 50, sort: '-created' }, { signal: c.req.raw.signal }) } catch (e) { if (e instanceof FetchError) return c.text('', e.status) throw e } if (!collection) return c.text('', 404) let author try { author = await Api.user.getById(collection.user.$id, { signal: c.req.raw.signal }) } catch (e) { if (e instanceof FetchError && e.message == 'email-not-confirmed') return c.text( `This feed is temporarily unavailable. The owner of this collection hasn't confirmed their email address yet. If you are the owner, see https://help.raindrop.io/public-page#why-is-my-public-collection-not-accessible`, 403 ) throw e } if (!author) return c.text('', 404) //redirect to original user if host is not equal const host = c.req.header('host')?.split('.')[0] if (author.name.toLowerCase() != host?.toLowerCase()) return c.redirect(`${collectionUrl(author, collection)}/feed`, 301) return c.body( renderFeed({ collection, items: raindrops.items || [], author }), 200, { 'Content-Type': 'application/rss+xml; charset=utf-8', 'Cache-Control': 'public,max-age=3600,stale-while-revalidate=300,stale-if-error=604800' } ) }