fediblock-instance/lib/util.js

47 lines
3.2 KiB
JavaScript
Raw Normal View History

2024-09-15 17:44:53 +00:00
module.exports = apex => {
2024-09-26 00:23:49 +00:00
const constant = require("./constant"),
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
2024-09-15 17:44:53 +00:00
}
2024-09-26 00:23:49 +00:00
} 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://${constant.apexdomain}/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 || (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 || 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(/\r?\n/g, '<br />')}</p>`,
tag: hashtags.concat(mentions),
attachment: images.concat(links).concat(audio).concat(video),
inReplyTo: reply || null
}
})
act.object[0].id = act.id
await apex.addToOutbox(await apex.store.getObject(apex.utils.usernameToIRI(id), true), act)
}
2024-09-15 17:44:53 +00:00
return { urlToId, sendFederatedMessage }
}