diff options
author | Volpeon <git@volpeon.ink> | 2021-10-17 16:54:53 +0200 |
---|---|---|
committer | Volpeon <git@volpeon.ink> | 2021-10-17 16:54:53 +0200 |
commit | 30b0adcacef48ac53aea13cbdc3288db0bd8d103 (patch) | |
tree | 402f4cc31a2fa4f0e746c81755b537b5f5137e4c /src/api/mastodon | |
download | feralbot-30b0adcacef48ac53aea13cbdc3288db0bd8d103.tar.gz feralbot-30b0adcacef48ac53aea13cbdc3288db0bd8d103.tar.bz2 feralbot-30b0adcacef48ac53aea13cbdc3288db0bd8d103.zip |
Init
Diffstat (limited to 'src/api/mastodon')
-rw-r--r-- | src/api/mastodon/index.ts | 58 |
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 @@ | |||
1 | import got from "got"; | ||
2 | import FormData from "form-data"; | ||
3 | import fileType from "file-type"; | ||
4 | import { nanoid } from "nanoid"; | ||
5 | import config from "../../config"; | ||
6 | |||
7 | export interface Attachment { | ||
8 | id: string; | ||
9 | } | ||
10 | |||
11 | export interface Status { | ||
12 | url: string; | ||
13 | } | ||
14 | |||
15 | export const client = got.extend({ | ||
16 | prefixUrl: config.mastodon.instance, | ||
17 | headers: { | ||
18 | Authorization: `Bearer ${config.mastodon.token}`, | ||
19 | }, | ||
20 | }); | ||
21 | |||
22 | export 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 | |||
32 | export 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 | } | ||