cmsetlbbq/src/mastodonComments.js

96 lines
3.0 KiB
JavaScript

const args = require('minimist')(process.argv.slice(2), {string: 'rootToot', boolean: 'fragment'})
// const htmlComment = require('./html/comment.js')
// const htmlCommentsPageTempate = require('./html/commentsPageTemplate.js')
// const geminiComment = require('./gemini/comment.js')
// const geminiCommentsPageTempate = require('./gemini/commentsTemplate.js')
const defaultArgs = {
rootToot: '109574160582937075',
tootSource: 'fosstodon.org',
fragment: false,
title: '',
backlink: '..',
format: 'html'
}
// const defaultArgs = {
// rootToot: '109309280260024223',
// tootSource: 'curious.simio.us'
// }
let { rootToot, tootSource, fragment, title, backlink, format } = { ...defaultArgs, ...args }
rootToot = String(rootToot)
let commentTpl
let commentPageTpl
switch(args.format) {
case 'gemini':
commentTpl = require('./gemini/comment.js')
commentPageTpl = require('./gemini/commentsTemplate.js')
break
case 'html':
default:
commentTpl = require('./html/comment.js')
commentPageTpl = require('./html/commentsPageTemplate.js')
break
}
const getMastodonComments = async (id) => {
const apiUrl = `https://${tootSource}/api/v1/statuses/${id}/context`
const response = await fetch(apiUrl)
const { descendants } = await response.json()
const tootString = renderToots(descendants, id, 0).join('\n')
return fragment ? tootString : commentPageTpl(tootString, title, backlink)
}
getMastodonComments(rootToot).then(console.log)
// the belowfollowing is adapted from
// https://danielpecos.com/2022/12/25/mastodon-as-comment-system-for-your-static-blog/
function getUserAccountString(account) {
var result = `@${account.acct}`;
if (account.acct.indexOf('@') === -1) {
var domain = new URL(account.url)
result += `@${domain.hostname}`
}
return result;
}
function renderToots(toots, in_reply_to, depth) {
var tootsToRender = toots
.filter(toot => toot.in_reply_to_id === in_reply_to)
.sort((a, b) => a.created_at.localeCompare(b.created_at));
return tootsToRender.flatMap(toot => renderToot(toots, toot, depth));
}
function renderToot(toots, toot, depth) {
const data = prepTootData(toot, depth)
const mastodonComment = commentTpl(data)
return [mastodonComment, ...renderToots(toots, toot.id, depth + 1)]
}
function prepTootData(toot, depth) {
return {
account: {
url: toot.account.url,
displayName: toot.account.display_name,
user: getUserAccountString(toot.account),
avatar: toot.account.avatar_static,
emojis: toot.account.emojis,
},
depth,
url: toot.url,
date: `${toot.created_at.substr(0, 10)} ${toot.created_at.substr(11, 8)}`,
content: toot.content,
attachments: toot.media_attachments,
counts: {
replies: toot.replies_count,
reblogs: toot.reblogs_count,
favourites: toot.favourites_count,
}
}
}