activitypress/src/command.ts

69 lines
2.0 KiB
TypeScript

import fs from "node:fs";
import markdownit from 'markdown-it'
import { slugRegex } from "./article.js";
import { newUser, get as getUserByNickname, getFollowerInboxes } from "./user.js";
import { insert as insertArticle } from "./article.js";
import { add as addToOutbox } from "./outbox.js";
import { createArticleActivity, sendAll } from "./activity.js";
import { fillRoute } from "./router.js";
const md = markdownit();
const c = process.argv[2];
let returnCode = 0;
if (c === "new-user") {
const nickname = process.argv[3];
const name = process.argv[4];
const bio = process.argv[5] || "";
const userId = await newUser(nickname, name, bio);
console.log(userId);
process.exit(0);
}
else if (c === "new-article") {
const nickname = process.argv[3];
const slug = process.argv[4];
const title = process.argv[5];
const images = process.argv.slice(6);
const user = await getUserByNickname(nickname);
if (!user) {
console.error("Nonexistent user");
process.exit(1);
}
if (!slugRegex.test(slug)) {
returnCode = 1;
console.error("Bad slug");
process.exit(returnCode);
}
const filename = `pages/${slug}.md`;
if (!fs.existsSync(filename)) {
console.error("No file with that slug");
process.exit(1);
}
const htmlFilename = `pages/${slug}.html`;
const markdown = fs.readFileSync(filename, "utf-8");
const html = md.render(markdown);
fs.writeFileSync(htmlFilename, html);
const article = await insertArticle(user.id, slug, title);
console.log(article.id);
await addToOutbox(article.id);
const keyId = fillRoute("actor", user.nickname) + "#main-key";
const inboxes = await getFollowerInboxes(user.id);
const activity = createArticleActivity(article, user);
const success = await sendAll(keyId, user.private_key, activity, inboxes);
process.exit(0);
}
else {
console.error("Unrecognized command: ", c);
returnCode = 1;
process.exit(returnCode);
}