import * as e621 from "./api/e621"; import * as mastodon from "./api/mastodon"; import config from "./config"; import Sharp from "sharp"; import * as cliArgs from "ts-command-line-args"; const args = cliArgs.parse<{ id?: number; help?: boolean; }>( { id: { type: Number, optional: true }, help: { type: Boolean, optional: true, alias: "h" }, }, { helpArg: "help", } ); async function postRandomPicture() { console.log("Fetching random post..."); const queryIndex = Math.floor(Math.random() * config.e621.queries.length); const query = config.e621.queries[queryIndex]; const post = await e621.getRandomPost(query); console.log(`Got ${post.id} via query ${queryIndex}`); await handlePost(post); } async function postSpecificPicture(id: number) { console.log(`Fetching post ${id}...`); const post = await e621.getPostById(id); console.log(`Got ${post.id}`); await handlePost(post); } async function handlePost(post: e621.Post) { const source = post.sources.length ? post.sources[0] : undefined; const cws = config.cw.filter((w) => post.tags.general.includes(w)); console.log(`Downloading image...`); let file = await e621.client.get(post.file.url).buffer(); if (Buffer.byteLength(file) > 1024 * 1024 * 9) { console.log(`Compressing...`); file = await Sharp(file) .resize(1000, 1000, { fit: "inside", withoutEnlargement: true }) .jpeg({ quality: 80, mozjpeg: true }) .toBuffer(); } console.log(`Uploading...`); const attachment = await mastodon.upload(file, post.id.toString(10)); console.log(`Posting status...`); const status = await mastodon.createStatus(`https://e926.net/posts/${post.id}`, source, cws, attachment.id); console.log(`Done! ${status.url}`); } (async () => { if (!config.mastodon.token) { console.error("MASTODON_TOKEN not set"); return; } if (args.id) { await postSpecificPicture(args.id); } else { await postRandomPicture(); } })();