fix: rss to masto text truncation

This commit is contained in:
Cory Dransfeldt 2024-09-26 11:44:36 -07:00
parent 3d97366667
commit bda81f70dd
No known key found for this signature in database
3 changed files with 37 additions and 24 deletions

View file

@ -30,6 +30,9 @@ async function handleMastodonPost(env) {
if (existingPost) continue
const title = item.title
const link = item.link
const maxLength = 500
const plainTextDescription = convert(item.description, {
wordwrap: false,
selectors: [
@ -40,12 +43,12 @@ async function handleMastodonPost(env) {
{ selector: '*', format: 'block' }
]
})
const content = `${item.title}\n\n${plainTextDescription}\n\n${item.link}`
const content = truncateContent(title, plainTextDescription, link, maxLength)
await postToMastodon(mastodonApiUrl, accessToken, content)
const timestamp = new Date().toISOString()
await env.RSS_TO_MASTODON_NAMESPACE.put(item.link, timestamp)
console.log(`Posted stored URL: ${item.link}`)
@ -57,6 +60,16 @@ async function handleMastodonPost(env) {
}
}
function truncateContent(title, description, link, maxLength) {
const baseLength = `${title}\n\n${link}`.length
const availableSpace = maxLength - baseLength - 4
let truncatedDescription = description
if (description.length > availableSpace) truncatedDescription = description.substring(0, availableSpace).split(' ').slice(0, -1).join(' ') + '...'
return `${title}\n\n${truncatedDescription}\n\n${link}`
}
async function fetchRSSFeed(rssFeedUrl) {
const response = await fetch(rssFeedUrl)
const rssText = await response.text()