-
-
Save gmph/02a44fc28f7da91da05462f7046ab19f to your computer and use it in GitHub Desktop.
Mastodon Blog Comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Handler } from '@netlify/functions'; | |
// I use Netlify, but this implementation can modified to work in many server environments | |
import fetch from 'node-fetch'; | |
import { MastodonStatus } from '../src/lib/mastodon'; | |
// Get a token from your Mastodon account preferences, e.g. mas.to/settings/applications/new. Create an app with 'read:notifications' and 'read:statuses' permissions. | |
const USER_ACCESS_TOKEN = 'ENTER_YOUR_TOKEN_HERE'; | |
// Add your own account details here: | |
const MASTODON_INSTANCE_DOMAIN = 'mas.to'; | |
const MASTODON_USERNAME = 'gmph'; | |
const MASTODON_USER_ID = '109331011229778444'; | |
const handler: Handler = async (event, context) => { | |
let conversationIds: string[]; | |
let path: string; | |
try { | |
path = decodeURIComponent(event.path.split('/')[3]); | |
conversationIds = decodeURIComponent(event.path.split('/')[4]).split(',').filter(id => !!id.length) as string[]; | |
} catch (error) { | |
return getError(error); | |
} | |
if (conversationIds.length === 0 && (!path.length || path[0] !== '/')) { | |
return getError({ error: 'A valid conversation ID or path is required' }); | |
} | |
try { | |
const knownStatusIds = conversationIds ? conversationIds : []; | |
const knownStatuses = await getStatusesByIds(knownStatusIds); | |
const relevantStatuses = await getRelevantStatusesForPath(path); | |
const relevantStatusIds = relevantStatuses.map(status => status.id); | |
const statusReplies = (await Promise.all([...knownStatusIds, ...relevantStatusIds].map(id => getStatusReplies(id)))).flat(); | |
return { | |
statusCode: 200, | |
headers: { 'Cache-Control': `public, s-maxage=${60 * 10}` }, | |
body: JSON.stringify({ | |
conversation_ids: [...knownStatusIds, ...relevantStatuses.filter(status => status.account.acct === `${MASTODON_USERNAME}@${MASTODON_INSTANCE_DOMAIN}`).map(status => status.id)], | |
replies: getSanitizedStatuses([...knownStatuses, ...relevantStatuses, ...statusReplies]), | |
}), | |
}; | |
} catch (error) { | |
return getError(error); | |
}; | |
} | |
const getStatusesByIds = async (ids: string[]): Promise<MastodonStatus[]> => { | |
const statuses = await Promise.all(ids.map(id => requestMastodon( | |
'GET', | |
'/api/v1/statuses/' + id | |
))); | |
return getSanitizedStatuses(statuses); | |
} | |
const getRelevantStatusesForPath = async (path: string): Promise<MastodonStatus[]> => { | |
const allMentions = await requestMastodonPaginated( | |
'GET', | |
'/api/v1/notifications', | |
{ 'types[]': 'mention', limit: 300 }, | |
{}, | |
true | |
); | |
const allOwnStatuses = await requestMastodonPaginated( | |
'GET', | |
'/api/v1/accounts/' + MASTODON_USER_ID + '/statuses', | |
{ exclude_reblogs: true, limit: 300 } | |
); | |
const sanitizedStatuses = getSanitizedStatuses([...allMentions.map(m => m['status']).filter(s => typeof !!s), ...allOwnStatuses]); | |
return sanitizedStatuses.filter(s => s.content.indexOf(path) > -1); | |
} | |
const getStatusReplies = async (id: string): Promise<MastodonStatus[]> => { | |
const ancestorsAndDecendents = await requestMastodon( | |
'GET', | |
'/api/v1/statuses/' + id + '/context' | |
); | |
return getSanitizedStatuses([...ancestorsAndDecendents['ancestors'], ...ancestorsAndDecendents['descendants']]); | |
} | |
const getSanitizedStatuses = (statuses: any[]): MastodonStatus[] => { | |
const sanitizedStatuses = statuses | |
.filter(s => { | |
return typeof s === 'object' && | |
typeof s['id'] === 'string'; | |
}) | |
.map(s => { | |
const username = s['account']['acct'].split('@')[0] || s['account']['username']; | |
const instance = s['account']['acct'].indexOf('@') > -1 ? s['account']['acct'].split('@')[1] : MASTODON_INSTANCE_DOMAIN; | |
return { | |
id: s['id'], | |
created_at: s['created_at'], | |
url: s['url'], | |
content: s['content'], | |
account: { | |
id: s['account']['id'], | |
acct: `${username}@${instance}`, | |
display_name: s['account']['display_name'], | |
url: s['account']['url'], | |
avatar: s['account']['avatar'], | |
avatar_static: s['account']['avatar_static'], | |
note: s['account']['note'], | |
}, | |
media_attachments: (s['media_attachments'] || []).map(m => ({ | |
id: m['id'], | |
type: m['type'], | |
url: m['url'], | |
})), | |
reblogs_count: parseInt(s['url']), | |
favourites_count: parseInt(s['url']), | |
} | |
}) | |
.sort((a, b) => { | |
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime(); | |
}); | |
return sanitizedStatuses; | |
} | |
export { handler }; | |
async function requestMastodonPaginated( | |
method: string, | |
path: string, | |
query: { [parameter: string]: any } = {}, | |
headers: { [header: string]: string } = {}, | |
authorized: boolean = false, | |
): Promise<any> { | |
const batchLimit = 30; | |
const limit = query['limit']; | |
if (typeof limit !== 'number' || limit <= 0) { | |
throw { error: `Request to ${path} aborted because an invalid limit was provided`, limit }; | |
} | |
const batchesToRequest = Math.ceil(limit / batchLimit); | |
let maxId = undefined; | |
const results = []; | |
for (let b = 0; b < batchesToRequest; b++) { | |
try { | |
const max_id = maxId ? { max_id: maxId } : {}; | |
const batchResults = await requestMastodon(method, path, { ...query, ...max_id, limit: batchLimit }, headers, authorized); | |
if (!batchResults || !batchResults.length) { | |
break; | |
} | |
results.push(...batchResults); | |
maxId = batchResults[batchResults.length - 1]['id']; | |
} catch (e) { | |
console.warn('Mastodon request batch failed, skipping', e); | |
} | |
} | |
return results; | |
} | |
async function requestMastodon( | |
method: string, | |
path: string, | |
query: { [parameter: string]: any } = {}, | |
headers: { [header: string]: string } = {}, | |
authorized: boolean = false, | |
): Promise<any> { | |
const authorization = authorized ? { | |
'authorization': `Bearer ${USER_ACCESS_TOKEN}` | |
} : {}; | |
const response = await fetch( | |
`https://${MASTODON_INSTANCE_DOMAIN}/${path}${getUrlParameterString(query)}`, | |
{ | |
method, | |
headers: { | |
...headers, | |
'accept': 'application/json', | |
...authorization, | |
} | |
}); | |
let data; | |
try { | |
data = response.json(); | |
} catch (error) { | |
data = {}; | |
throw { error: `Failed to parse JSON response from successful request to ${path}` }; | |
} | |
if (response.status.toString()[0] !== '2') { | |
throw { error: `Request to ${path} resulted in status ${response.status}`, data }; | |
} | |
return data; | |
} | |
const getError = (error) => { | |
let parsedError; | |
try { | |
parsedError = JSON.stringify(error); | |
} | |
catch (e) { | |
parsedError = error.toString(); | |
} | |
return { | |
statusCode: 500, | |
body: parsedError, | |
} | |
}; | |
const getUrlParameterString = (parameters: { [parameter: string]: any }): string => | |
Object.entries(parameters).length ? '?' + Object.entries(parameters).map(kv => kv.map(s => encodeURIComponent(s.toString())).join("=")).join("&") : ''; | |
/* ############################################################################ | |
MIT License | |
Copyright (c) 2022 Graham Macphee | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
############################################################################ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment