chore: refactoring

This commit is contained in:
Cory Dransfeldt 2024-10-08 17:35:26 -07:00
parent df5fddefc0
commit e0593447eb
No known key found for this signature in database
40 changed files with 181 additions and 232 deletions

View file

@ -1,5 +1,8 @@
import { XMLParser } from 'fast-xml-parser'
import { convert } from 'html-to-text'
import { createClient } from '@supabase/supabase-js'
const BASE_URL = 'https://coryd.dev'
export default {
async scheduled(event, env, ctx) {
@ -20,6 +23,9 @@ async function handleMastodonPost(env) {
const mastodonApiUrl = 'https://follow.coryd.dev/api/v1/statuses'
const accessToken = env.MASTODON_ACCESS_TOKEN
const rssFeedUrl = 'https://coryd.dev/feeds/all'
const supabaseUrl = env.SUPABASE_URL
const supabaseKey = env.SUPABASE_KEY
const supabase = createClient(supabaseUrl, supabaseKey)
try {
const latestItems = await fetchRSSFeed(rssFeedUrl)
@ -47,13 +53,18 @@ async function handleMastodonPost(env) {
const cleanedDescription = plainTextDescription.replace(/\s+/g, ' ').trim()
const content = truncateContent(title, cleanedDescription, link, maxLength)
await postToMastodon(mastodonApiUrl, accessToken, content)
const mastodonPostUrl = await postToMastodon(mastodonApiUrl, accessToken, content)
const timestamp = new Date().toISOString()
await env.RSS_TO_MASTODON_NAMESPACE.put(item.link, timestamp)
await env.RSS_TO_MASTODON_NAMESPACE.put(link, timestamp)
console.log(`Posted stored URL: ${item.link}`)
if (link.includes('coryd.dev/posts')) {
const slug = link.replace(BASE_URL, '')
await addMastodonUrlToPost(supabase, slug, mastodonPostUrl)
}
console.log(`Posted stored URL: ${link}`)
}
console.log('RSS processed successfully')
@ -62,6 +73,19 @@ async function handleMastodonPost(env) {
}
}
async function addMastodonUrlToPost(supabase, slug, mastodonPostUrl) {
const { data, error } = await supabase
.from('posts')
.update({ mastodon_url: mastodonPostUrl })
.eq('slug', slug)
if (error) {
console.error('Error updating post:', error)
} else {
console.log(`Updated post with Mastodon URL: ${mastodonPostUrl}`)
}
}
function truncateContent(title, description, link, maxLength) {
const baseLength = `${title}\n\n${link}`.length
const availableSpace = maxLength - baseLength - 4
@ -106,5 +130,9 @@ async function postToMastodon(apiUrl, accessToken, content) {
throw new Error(`Error posting to Mastodon: ${response.statusText} - ${errorText}`)
}
const responseData = await response.json()
console.log('Posted to Mastodon successfully.')
return responseData.url
}

View file

@ -1,26 +1,4 @@
import { createClient } from '@supabase/supabase-js'
import slugify from 'slugify'
const sanitizeMediaString = (str) => {
const sanitizedString = str.normalize('NFD').replace(/[\u0300-\u036f\u2010—\.\?\(\)\[\]\{\}]/g, '').replace(/\.{3}/g, '')
return slugify(sanitizedString, {
replacement: '-',
remove: /[#,&,+()$~%.'":*?<>{}]/g,
lower: true,
})
}
const regionNames = new Intl.DisplayNames(['en'], { type: 'region' })
const getCountryName = (countryCode) => regionNames.of(countryCode.trim()) || countryCode.trim()
const parseCountryField = (countryField) => {
if (!countryField) return null
const delimiters = /[,\/&and]+/
const countries = countryField.split(delimiters)
return countries.map(getCountryName).join(', ')
}
export default {
async fetch(request, env) {
@ -49,7 +27,7 @@ export default {
const emoji = data.artist_emoji || genreEmoji
return new Response(JSON.stringify({
content: `${emoji || '🎧'} ${data.track_name} by <a href="https://coryd.dev/music/artists/${sanitizeMediaString(data.artist_name)}-${sanitizeMediaString(parseCountryField(data.artist_country))}">${data.artist_name}</a>`,
content: `${emoji || '🎧'} ${data.track_name} by <a href="https://coryd.dev${data.url}">${data.artist_name}</a>`,
}), { headers })
}
}

View file

@ -114,6 +114,7 @@ export default {
mbid: null,
art: '4cef75db-831f-4f5d-9333-79eaa5bb55ee',
name: artistName,
slug: '/music',
tentative: true,
total_plays: 0,
},