fediblock-instance/lib/util.js

46 lines
3.0 KiB
JavaScript
Raw Permalink Normal View History

2024-09-15 17:44:53 +00:00
module.exports = apex => {
const urlToId = url => {
try {
if (typeof new URL(url) === 'object' && url.split('/').length === 5 && url.split('/')[3].length > 0) {
return '@' + url.split('/')[4] + '@' + url.split('/')[2]
} else {
return url
}
} catch (e) {
return url
}
},
sendFederatedMessage = async (id, summary, message, recipient, reply) => {
const users = message.split(' ').filter(token => token.startsWith('@') && token.split('@').length === 3)
.map(token => `https://${token.split('@')[2]}/users/${token.split('@')[1]}`),
mentions = message.split(' ').filter(token => token.startsWith('@') && token.split('@').length === 3)
.map(token => { return { type: 'Mention', href: `https://${token.split('@')[2]}/users/${token.split('@')[1]}`, name: `@${token.split('@')[1]}` } }),
hashtags = message.split(' ').filter(token => token.startsWith('#'))
.map(token => { return { id: `https://mastodon.social/tags/${token.split('#')[1]}`, name: token } }),
images = message.split(' ').filter(token => token.match(/^https?:\/\//i) && token.match(/\.(jpg|png|gif|jpeg|ppm)$/i))
.map(token => { return { type: 'Image', url: token } }),
audio = message.split(' ').filter(token => token.match(/^https?:\/\//i) && token.match(/\.(mp3|wav|flac)$/i))
.map(token => { return { type: 'Audio', url: token } }),
video = message.split(' ').filter(token => token.match(/^https?:\/\//i) && token.match(/\.(mp4|flv|avi)$/i))
.map(token => { return { type: 'Video', url: token } }),
links = message.split(' ').filter(token => token.match(/^https?:\/\//i) && !images.concat(audio).concat(video)
.some(link => link.url === token)).map(token => { return { type: 'Link', href: token } }),
allusers = users.concat([recipient ? recipient : (await apex.store.getObject(apex.utils.usernameToIRI(id), true)).followers[0]]),
act = await apex.buildActivity('Create', apex.utils.usernameToIRI(id), ['https://www.w3.org/ns/activitystreams#Public'].concat(allusers), {
object: {
type: 'Note',
name: `Fediblock Instance`,
summary: summary ? summary : null,
content: `<p>${message.replace(/(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*))/ig,
'<a href="$1" target="_blank">$3</a>').replace(/\s#(\S+)/g, '<a href="https://mastodon.social/tags/$1">#$1</a>').replace(new RegExp('\r?\n', 'g'), '<br />')}</p>`,
tag: hashtags.concat(mentions),
attachment: images.concat(links).concat(audio).concat(video),
inReplyTo: reply ? reply : null
}
})
act.object[0].id = act.id
await apex.addToOutbox(await apex.store.getObject(apex.utils.usernameToIRI(id), true), act)
}
return { urlToId, sendFederatedMessage }
}