generated from nhcarrigan/template
feat: more automated announcements (#8)
### Explanation Makes my life so much easier. ### Issue _No response_ ### Attestations - [x] I have read and agree to the [Code of Conduct](https://docs.nhcarrigan.com/community/coc/) - [x] I have read and agree to the [Community Guidelines](https://docs.nhcarrigan.com/community/guide/). - [x] My contribution complies with the [Contributor Covenant](https://docs.nhcarrigan.com/dev/covenant/). ### Dependencies - [x] I have pinned the dependencies to a specific patch version. ### Style - [x] I have run the linter and resolved any errors. - [x] My pull request uses an appropriate title, matching the conventional commit standards. - [x] My scope of feat/fix/chore/etc. correctly matches the nature of changes in my pull request. ### Tests - [ ] My contribution adds new code, and I have added tests to cover it. - [ ] My contribution modifies existing code, and I have updated the tests to reflect these changes. - [ ] All new and existing tests pass locally with my changes. - [ ] Code coverage remains at or above the configured threshold. ### Documentation _No response_ ### Versioning Minor - My pull request introduces a new non-breaking feature. Reviewed-on: #8 Co-authored-by: Naomi Carrigan <commits@nhcarrigan.com> Co-committed-by: Naomi Carrigan <commits@nhcarrigan.com>
This commit was merged in pull request #8.
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @copyright nhcarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
|
||||
import { isValidString } from "../utils/typeguards.js";
|
||||
|
||||
/**
|
||||
* Forwards an announcement to our Mastodon account.
|
||||
* @param content - The main body of the announcement.
|
||||
* @returns A message indicating the success or failure of the operation.
|
||||
*/
|
||||
// eslint-disable-next-line max-lines-per-function, max-statements, complexity -- This is a big function.
|
||||
export const announceOnMastodon = async(
|
||||
content: Array<string>,
|
||||
): Promise<string> => {
|
||||
if (
|
||||
process.env.MASTODON_INSTANCE_URL === undefined
|
||||
|| process.env.MASTODON_ACCESS_TOKEN === undefined
|
||||
) {
|
||||
return "Mastodon credentials are not set.";
|
||||
}
|
||||
const [ firstPost, ...restOfPosts ] = content;
|
||||
const failedReplies: Array<string> = [];
|
||||
if (firstPost === undefined) {
|
||||
return "No posts to send to Mastodon.";
|
||||
}
|
||||
const instanceUrl = process.env.MASTODON_INSTANCE_URL.replace(/\/$/, "");
|
||||
const accessToken = process.env.MASTODON_ACCESS_TOKEN;
|
||||
const apiUrl = `${instanceUrl}/api/v1/statuses`;
|
||||
const headers = {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- HTTP header name.
|
||||
"Authorization": `Bearer ${accessToken}`,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- HTTP header name.
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
const firstPostResponse = await fetch(apiUrl, {
|
||||
body: JSON.stringify({ status: firstPost }),
|
||||
headers: headers,
|
||||
method: "POST",
|
||||
}).catch((error: unknown) => {
|
||||
return error instanceof Error
|
||||
? error.message
|
||||
: String(error);
|
||||
});
|
||||
if (typeof firstPostResponse === "string") {
|
||||
return `Failed to send initial post to Mastodon. ${firstPostResponse}`;
|
||||
}
|
||||
if (!firstPostResponse.ok) {
|
||||
const errorText = await firstPostResponse.text().catch(() => {
|
||||
return firstPostResponse.statusText;
|
||||
});
|
||||
return `Failed to send initial post to Mastodon. Status: ${firstPostResponse.status.toString()} ${errorText}`;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Fetch does not accept generics.
|
||||
const firstPostData = await firstPostResponse.json() as { id?: string };
|
||||
if (firstPostData.id === undefined) {
|
||||
return `Failed to parse initial post ID from Mastodon. ${JSON.stringify(firstPostData)}`;
|
||||
}
|
||||
let inReplyToId = firstPostData.id;
|
||||
for (const post of restOfPosts) {
|
||||
// eslint-disable-next-line no-await-in-loop -- We need to do this sequentially.
|
||||
const replyResponse = await fetch(apiUrl, {
|
||||
body: JSON.stringify({
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- API requirement.
|
||||
in_reply_to_id: inReplyToId,
|
||||
status: post,
|
||||
}),
|
||||
headers: headers,
|
||||
method: "POST",
|
||||
}).catch((error: unknown) => {
|
||||
return error instanceof Error
|
||||
? error.message
|
||||
: String(error);
|
||||
});
|
||||
if (typeof replyResponse === "string") {
|
||||
failedReplies.push(post);
|
||||
continue;
|
||||
}
|
||||
if (!replyResponse.ok) {
|
||||
failedReplies.push(post);
|
||||
continue;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, no-await-in-loop -- Fetch does not accept generics.
|
||||
const replyData = await replyResponse.json() as { id?: string };
|
||||
if (isValidString(replyData.id)) {
|
||||
inReplyToId = replyData.id;
|
||||
continue;
|
||||
}
|
||||
failedReplies.push(post);
|
||||
}
|
||||
return `Successfully sent initial post to Mastodon. ${failedReplies.length > 0
|
||||
? `Failed to send ${failedReplies.length.toString()} replies: ${failedReplies.join(", ")}`
|
||||
: `All ${(content.length - 1).toString()} replies were sent successfully.`}`;
|
||||
};
|
||||
Reference in New Issue
Block a user