From 30b0adcacef48ac53aea13cbdc3288db0bd8d103 Mon Sep 17 00:00:00 2001 From: Volpeon Date: Sun, 17 Oct 2021 16:54:53 +0200 Subject: Init --- src/api/mastodon/index.ts | 58 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/api/mastodon/index.ts (limited to 'src/api/mastodon') diff --git a/src/api/mastodon/index.ts b/src/api/mastodon/index.ts new file mode 100644 index 0000000..2d8636e --- /dev/null +++ b/src/api/mastodon/index.ts @@ -0,0 +1,58 @@ +import got from "got"; +import FormData from "form-data"; +import fileType from "file-type"; +import { nanoid } from "nanoid"; +import config from "../../config"; + +export interface Attachment { + id: string; +} + +export interface Status { + url: string; +} + +export const client = got.extend({ + prefixUrl: config.mastodon.instance, + headers: { + Authorization: `Bearer ${config.mastodon.token}`, + }, +}); + +export async function upload(buf: Buffer, filename: string) { + const type = await fileType.fromBuffer(buf); + + const body = new FormData(); + body.append("i", config.mastodon.token); + body.append("file", buf, { filename: `${filename}.${type.ext}`, contentType: type.mime }); + + return client.post("api/v1/media", { body }).json(); +} + +export async function createStatus( + postUrl: string, + sourceUrl: string | undefined, + spoiler: string[], + attachmentId: string +) { + let lines = [postUrl]; + if (sourceUrl) { + lines.push(`Source: ${sourceUrl}`); + } + + const spoilerText = spoiler.length ? `CW: ${spoiler.join(", ")}` : undefined; + + return client + .post("api/v1/statuses", { + headers: { + "Idempotency-Key": nanoid(), + }, + json: { + status: lines.join("\n"), + media_ids: [attachmentId], + sensitive: true, + spoiler_text: spoilerText, + }, + }) + .json(); +} -- cgit v1.2.3-70-g09d2