summaryrefslogtreecommitdiffstats
path: root/src/api/mastodon
diff options
context:
space:
mode:
Diffstat (limited to 'src/api/mastodon')
-rw-r--r--src/api/mastodon/index.ts58
1 files changed, 58 insertions, 0 deletions
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 @@
1import got from "got";
2import FormData from "form-data";
3import fileType from "file-type";
4import { nanoid } from "nanoid";
5import config from "../../config";
6
7export interface Attachment {
8 id: string;
9}
10
11export interface Status {
12 url: string;
13}
14
15export const client = got.extend({
16 prefixUrl: config.mastodon.instance,
17 headers: {
18 Authorization: `Bearer ${config.mastodon.token}`,
19 },
20});
21
22export async function upload(buf: Buffer, filename: string) {
23 const type = await fileType.fromBuffer(buf);
24
25 const body = new FormData();
26 body.append("i", config.mastodon.token);
27 body.append("file", buf, { filename: `${filename}.${type.ext}`, contentType: type.mime });
28
29 return client.post("api/v1/media", { body }).json<Attachment>();
30}
31
32export async function createStatus(
33 postUrl: string,
34 sourceUrl: string | undefined,
35 spoiler: string[],
36 attachmentId: string
37) {
38 let lines = [postUrl];
39 if (sourceUrl) {
40 lines.push(`Source: ${sourceUrl}`);
41 }
42
43 const spoilerText = spoiler.length ? `CW: ${spoiler.join(", ")}` : undefined;
44
45 return client
46 .post("api/v1/statuses", {
47 headers: {
48 "Idempotency-Key": nanoid(),
49 },
50 json: {
51 status: lines.join("\n"),
52 media_ids: [attachmentId],
53 sensitive: true,
54 spoiler_text: spoilerText,
55 },
56 })
57 .json<Status>();
58}