Replace eslint and prettier with Biome

This commit is contained in:
Jesse Wierzbinski 2024-04-06 19:30:49 -10:00
parent 4a5a2ea590
commit af0d627f19
No known key found for this signature in database
199 changed files with 16493 additions and 16361 deletions

View file

@ -1,22 +1,22 @@
module.exports = {
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/strict-type-checked",
"plugin:@typescript-eslint/stylistic",
"plugin:prettier/recommended",
],
parser: "@typescript-eslint/parser",
parserOptions: {
project: "./tsconfig.json",
},
ignorePatterns: ["node_modules/", "dist/", ".eslintrc.cjs"],
plugins: ["@typescript-eslint"],
root: true,
rules: {
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/consistent-type-exports": "error",
"@typescript-eslint/consistent-type-imports": "error"
},
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/strict-type-checked",
"plugin:@typescript-eslint/stylistic",
"plugin:prettier/recommended",
],
parser: "@typescript-eslint/parser",
parserOptions: {
project: "./tsconfig.json",
},
ignorePatterns: ["node_modules/", "dist/", ".eslintrc.cjs"],
plugins: ["@typescript-eslint"],
root: true,
rules: {
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/consistent-type-exports": "error",
"@typescript-eslint/consistent-type-imports": "error",
},
};

5
.vscode/launch.json vendored
View file

@ -4,10 +4,7 @@
"type": "node",
"name": "vscode-jest-tests.v2.lysand",
"request": "launch",
"args": [
"test",
"${jest.testFile}"
],
"args": ["test", "${jest.testFile}"],
"cwd": "/home/jessew/Dev/lysand",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",

View file

@ -1,5 +1,5 @@
{
"typescript.tsdk": "node_modules/typescript/lib",
"jest.jestCommandLine": "/home/jessew/.bun/bin/bun test",
"jest.rootPath": "."
"typescript.tsdk": "node_modules/typescript/lib",
"jest.jestCommandLine": "/home/jessew/.bun/bin/bun test",
"jest.rootPath": "."
}

View file

@ -4,11 +4,11 @@ const requests: Promise<Response>[] = [];
// Repeat 1000 times
for (let i = 0; i < 1000; i++) {
requests.push(
fetch(`https://mastodon.social`, {
method: "GET",
})
);
requests.push(
fetch("https://mastodon.social", {
method: "GET",
}),
);
}
await Promise.all(requests);

View file

@ -9,46 +9,46 @@ const token = process.env.TOKEN;
const requestCount = Number(process.argv[2]) || 100;
if (!token) {
console.log(
`${chalk.red(
"✗"
)} No token provided. Provide one via the TOKEN environment variable.`
);
process.exit(1);
console.log(
`${chalk.red(
"✗",
)} No token provided. Provide one via the TOKEN environment variable.`,
);
process.exit(1);
}
const fetchTimeline = () =>
fetch(`${config.http.base_url}/api/v1/timelines/home`, {
headers: {
Authorization: `Bearer ${token}`,
},
}).then(res => res.ok);
fetch(`${config.http.base_url}/api/v1/timelines/home`, {
headers: {
Authorization: `Bearer ${token}`,
},
}).then((res) => res.ok);
const timeNow = performance.now();
const requests = Array.from({ length: requestCount }, () => fetchTimeline());
Promise.all(requests)
.then(results => {
const timeTaken = performance.now() - timeNow;
if (results.every(t => t)) {
console.log(`${chalk.green("✓")} All requests succeeded`);
} else {
console.log(
`${chalk.red("✗")} ${
results.filter(t => !t).length
} requests failed`
);
}
console.log(
`${chalk.green("✓")} ${
requests.length
} requests fulfilled in ${chalk.bold(
(timeTaken / 1000).toFixed(5)
)}s`
);
})
.catch(err => {
console.log(`${chalk.red("✗")} ${err}`);
process.exit(1);
});
.then((results) => {
const timeTaken = performance.now() - timeNow;
if (results.every((t) => t)) {
console.log(`${chalk.green("✓")} All requests succeeded`);
} else {
console.log(
`${chalk.red("✗")} ${
results.filter((t) => !t).length
} requests failed`,
);
}
console.log(
`${chalk.green("✓")} ${
requests.length
} requests fulfilled in ${chalk.bold(
(timeTaken / 1000).toFixed(5),
)}s`,
);
})
.catch((err) => {
console.log(`${chalk.red("✗")} ${err}`);
process.exit(1);
});

View file

@ -1,17 +1,20 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 4
}
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
"organizeImports": {
"enabled": true,
"ignore": ["node_modules/**/*", "dist/**/*"]
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
},
"ignore": ["node_modules/**/*", "dist/**/*"]
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 4,
"ignore": ["node_modules/**/*", "dist/**/*"]
}
}

View file

@ -1,52 +1,52 @@
// Delete dist directory
import { rm, cp, mkdir, exists } from "fs/promises";
import { cp, exists, mkdir, rm } from "node:fs/promises";
import { rawRoutes } from "~routes";
if (!(await exists("./pages/dist"))) {
console.log("Please build the Vite server first, or use `bun prod-build`");
process.exit(1);
console.log("Please build the Vite server first, or use `bun prod-build`");
process.exit(1);
}
console.log(`Building at ${process.cwd()}`);
await rm("./dist", { recursive: true });
await mkdir(process.cwd() + "/dist");
await mkdir(`${process.cwd()}/dist`);
//bun build --entrypoints ./index.ts ./prisma.ts ./cli.ts --outdir dist --target bun --splitting --minify --external bullmq,@prisma/client
await Bun.build({
entrypoints: [
process.cwd() + "/index.ts",
process.cwd() + "/prisma.ts",
process.cwd() + "/cli.ts",
// Force Bun to include endpoints
...Object.values(rawRoutes),
],
outdir: process.cwd() + "/dist",
target: "bun",
splitting: true,
minify: true,
external: ["bullmq"],
}).then(output => {
if (!output.success) {
console.log(output.logs);
}
entrypoints: [
`${process.cwd()}/index.ts`,
`${process.cwd()}/prisma.ts`,
`${process.cwd()}/cli.ts`,
// Force Bun to include endpoints
...Object.values(rawRoutes),
],
outdir: `${process.cwd()}/dist`,
target: "bun",
splitting: true,
minify: true,
external: ["bullmq"],
}).then((output) => {
if (!output.success) {
console.log(output.logs);
}
});
// Create pages directory
// mkdir ./dist/pages
await mkdir(process.cwd() + "/dist/pages");
await mkdir(`${process.cwd()}/dist/pages`);
// Copy Vite build output to dist
// cp -r ./pages/dist ./dist/pages
await cp(process.cwd() + "/pages/dist", process.cwd() + "/dist/pages/", {
recursive: true,
await cp(`${process.cwd()}/pages/dist`, `${process.cwd()}/dist/pages/`, {
recursive: true,
});
// Copy the Bee Movie script from pages
await cp(
process.cwd() + "/pages/beemovie.txt",
process.cwd() + "/dist/pages/beemovie.txt"
`${process.cwd()}/pages/beemovie.txt`,
`${process.cwd()}/dist/pages/beemovie.txt`,
);
console.log(`Built!`);
console.log("Built!");

BIN
bun.lockb

Binary file not shown.

View file

@ -1,64 +0,0 @@
import type { APActivity, APActor } from "activitypub-types";
export class RemoteActor {
private actorData: APActor | null;
private actorUri: string;
constructor(actor: APActor | string) {
if (typeof actor === "string") {
this.actorUri = actor;
this.actorData = null;
} else {
this.actorUri = actor.id || "";
this.actorData = actor;
}
}
public async fetch() {
const response = await fetch(this.actorUri);
const actorJson = (await response.json()) as APActor;
this.actorData = actorJson;
}
public getData() {
return this.actorData;
}
}
export class RemoteActivity {
private data: APActivity | null;
private uri: string;
constructor(uri: string, data: APActivity | null) {
this.uri = uri;
this.data = data;
}
public async fetch() {
const response = await fetch(this.uri);
const json = (await response.json()) as APActivity;
this.data = json;
}
public getData() {
return this.data;
}
public async getActor() {
if (!this.data) {
throw new Error("No data");
}
if (Array.isArray(this.data.actor)) {
throw new Error("Multiple actors");
}
if (typeof this.data.actor === "string") {
const actor = new RemoteActor(this.data.actor);
await actor.fetch();
return actor.getData();
}
return new RemoteActor(this.data.actor as any);
}
}

3540
cli.ts

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@ import { PrismaClient } from "@prisma/client";
import { config } from "config-manager";
const client = new PrismaClient({
datasourceUrl: `postgresql://${config.database.username}:${config.database.password}@${config.database.host}:${config.database.port}/${config.database.database}`,
datasourceUrl: `postgresql://${config.database.username}:${config.database.password}@${config.database.host}:${config.database.port}/${config.database.database}`,
});
/* const federationQueue = new Queue("federation", {

View file

@ -1,6 +1,6 @@
import type { APIApplication } from "~types/entities/application";
import type { Application } from "@prisma/client";
import { client } from "~database/datasource";
import type { APIApplication } from "~types/entities/application";
/**
* Represents an application that can authenticate with the API.
@ -12,18 +12,18 @@ import { client } from "~database/datasource";
* @returns The application associated with the given access token, or null if no such application exists.
*/
export const getFromToken = async (
token: string
token: string,
): Promise<Application | null> => {
const dbToken = await client.token.findFirst({
where: {
access_token: token,
},
include: {
application: true,
},
});
const dbToken = await client.token.findFirst({
where: {
access_token: token,
},
include: {
application: true,
},
});
return dbToken?.application || null;
return dbToken?.application || null;
};
/**
@ -31,9 +31,9 @@ export const getFromToken = async (
* @returns The API application representation of this application.
*/
export const applicationToAPI = (app: Application): APIApplication => {
return {
name: app.name,
website: app.website,
vapid_key: app.vapid_key,
};
return {
name: app.name,
website: app.website,
vapid_key: app.vapid_key,
};
};

View file

@ -1,69 +1,70 @@
import type { Attachment } from "@prisma/client";
import type { ConfigType } from "config-manager";
import type { Config } from "config-manager";
import { MediaBackendType } from "media-manager";
import type { APIAsyncAttachment } from "~types/entities/async_attachment";
import type { APIAttachment } from "~types/entities/attachment";
export const attachmentToAPI = (
attachment: Attachment
attachment: Attachment,
): APIAsyncAttachment | APIAttachment => {
let type = "unknown";
let type = "unknown";
if (attachment.mime_type.startsWith("image/")) {
type = "image";
} else if (attachment.mime_type.startsWith("video/")) {
type = "video";
} else if (attachment.mime_type.startsWith("audio/")) {
type = "audio";
}
if (attachment.mime_type.startsWith("image/")) {
type = "image";
} else if (attachment.mime_type.startsWith("video/")) {
type = "video";
} else if (attachment.mime_type.startsWith("audio/")) {
type = "audio";
}
return {
id: attachment.id,
type: type as any,
url: attachment.url,
remote_url: attachment.remote_url,
preview_url: attachment.thumbnail_url,
text_url: null,
meta: {
width: attachment.width || undefined,
height: attachment.height || undefined,
fps: attachment.fps || undefined,
size:
attachment.width && attachment.height
? `${attachment.width}x${attachment.height}`
: undefined,
duration: attachment.duration || undefined,
length: attachment.size?.toString() || undefined,
aspect:
attachment.width && attachment.height
? attachment.width / attachment.height
: undefined,
original: {
width: attachment.width || undefined,
height: attachment.height || undefined,
size:
attachment.width && attachment.height
? `${attachment.width}x${attachment.height}`
: undefined,
aspect:
attachment.width && attachment.height
? attachment.width / attachment.height
: undefined,
},
// Idk whether size or length is the right value
},
description: attachment.description,
blurhash: attachment.blurhash,
};
return {
id: attachment.id,
type: type as "image" | "video" | "audio" | "unknown",
url: attachment.url,
remote_url: attachment.remote_url,
preview_url: attachment.thumbnail_url,
text_url: null,
meta: {
width: attachment.width || undefined,
height: attachment.height || undefined,
fps: attachment.fps || undefined,
size:
attachment.width && attachment.height
? `${attachment.width}x${attachment.height}`
: undefined,
duration: attachment.duration || undefined,
length: attachment.size?.toString() || undefined,
aspect:
attachment.width && attachment.height
? attachment.width / attachment.height
: undefined,
original: {
width: attachment.width || undefined,
height: attachment.height || undefined,
size:
attachment.width && attachment.height
? `${attachment.width}x${attachment.height}`
: undefined,
aspect:
attachment.width && attachment.height
? attachment.width / attachment.height
: undefined,
},
// Idk whether size or length is the right value
},
description: attachment.description,
blurhash: attachment.blurhash,
};
};
export const getUrl = (name: string, config: ConfigType) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
if (config.media.backend === MediaBackendType.LOCAL) {
return `${config.http.base_url}/media/${name}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison, @typescript-eslint/no-unnecessary-condition
} else if (config.media.backend === MediaBackendType.S3) {
return `${config.s3.public_url}/${name}`;
}
return "";
export const getUrl = (name: string, config: Config) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
if (config.media.backend === MediaBackendType.LOCAL) {
return `${config.http.base_url}/media/${name}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison, @typescript-eslint/no-unnecessary-condition
}
if (config.media.backend === MediaBackendType.S3) {
return `${config.s3.public_url}/${name}`;
}
return "";
};

View file

@ -1,7 +1,7 @@
import type { Emoji } from "@prisma/client";
import { client } from "~database/datasource";
import type { APIEmoji } from "~types/entities/emoji";
import type { Emoji as LysandEmoji } from "~types/lysand/extensions/org.lysand/custom_emojis";
import { client } from "~database/datasource";
import type { Emoji } from "@prisma/client";
/**
* Represents an emoji entity in the database.
@ -13,41 +13,41 @@ import type { Emoji } from "@prisma/client";
* @returns An array of emojis
*/
export const parseEmojis = async (text: string): Promise<Emoji[]> => {
const regex = /:[a-zA-Z0-9_]+:/g;
const matches = text.match(regex);
if (!matches) return [];
return await client.emoji.findMany({
where: {
shortcode: {
in: matches.map(match => match.replace(/:/g, "")),
},
instanceId: null,
},
include: {
instance: true,
},
});
const regex = /:[a-zA-Z0-9_]+:/g;
const matches = text.match(regex);
if (!matches) return [];
return await client.emoji.findMany({
where: {
shortcode: {
in: matches.map((match) => match.replace(/:/g, "")),
},
instanceId: null,
},
include: {
instance: true,
},
});
};
export const addEmojiIfNotExists = async (emoji: LysandEmoji) => {
const existingEmoji = await client.emoji.findFirst({
where: {
shortcode: emoji.name,
instance: null,
},
});
const existingEmoji = await client.emoji.findFirst({
where: {
shortcode: emoji.name,
instance: null,
},
});
if (existingEmoji) return existingEmoji;
if (existingEmoji) return existingEmoji;
return await client.emoji.create({
data: {
shortcode: emoji.name,
url: emoji.url[0].content,
alt: emoji.alt || null,
content_type: emoji.url[0].content_type,
visible_in_picker: true,
},
});
return await client.emoji.create({
data: {
shortcode: emoji.name,
url: emoji.url[0].content,
alt: emoji.alt || null,
content_type: emoji.url[0].content_type,
visible_in_picker: true,
},
});
};
/**
@ -55,43 +55,43 @@ export const addEmojiIfNotExists = async (emoji: LysandEmoji) => {
* @returns The APIEmoji object.
*/
export const emojiToAPI = (emoji: Emoji): APIEmoji => {
return {
shortcode: emoji.shortcode,
static_url: emoji.url, // TODO: Add static version
url: emoji.url,
visible_in_picker: emoji.visible_in_picker,
category: undefined,
};
return {
shortcode: emoji.shortcode,
static_url: emoji.url, // TODO: Add static version
url: emoji.url,
visible_in_picker: emoji.visible_in_picker,
category: undefined,
};
};
export const emojiToLysand = (emoji: Emoji): LysandEmoji => {
return {
name: emoji.shortcode,
url: [
{
content: emoji.url,
content_type: emoji.content_type,
},
],
alt: emoji.alt || undefined,
};
return {
name: emoji.shortcode,
url: [
{
content: emoji.url,
content_type: emoji.content_type,
},
],
alt: emoji.alt || undefined,
};
};
/**
* Converts the emoji to an ActivityPub object.
* @returns The ActivityPub object.
*/
export const emojiToActivityPub = (emoji: Emoji): any => {
// replace any with your ActivityPub Emoji type
return {
type: "Emoji",
name: `:${emoji.shortcode}:`,
updated: new Date().toISOString(),
icon: {
type: "Image",
url: emoji.url,
mediaType: emoji.content_type,
alt: emoji.alt || undefined,
},
};
export const emojiToActivityPub = (emoji: Emoji): object => {
// replace any with your ActivityPub Emoji type
return {
type: "Emoji",
name: `:${emoji.shortcode}:`,
updated: new Date().toISOString(),
icon: {
type: "Image",
url: emoji.url,
mediaType: emoji.content_type,
alt: emoji.alt || undefined,
},
};
};

View file

@ -12,38 +12,38 @@ import type { ServerMetadata } from "~types/lysand/Object";
* @returns Either the database instance if it already exists, or a newly created instance.
*/
export const addInstanceIfNotExists = async (
url: string
url: string,
): Promise<Instance> => {
const origin = new URL(url).origin;
const hostname = new URL(url).hostname;
const origin = new URL(url).origin;
const hostname = new URL(url).hostname;
const found = await client.instance.findFirst({
where: {
base_url: hostname,
},
});
const found = await client.instance.findFirst({
where: {
base_url: hostname,
},
});
if (found) return found;
if (found) return found;
// Fetch the instance configuration
const metadata = (await fetch(`${origin}/.well-known/lysand`).then(res =>
res.json()
)) as Partial<ServerMetadata>;
// Fetch the instance configuration
const metadata = (await fetch(`${origin}/.well-known/lysand`).then((res) =>
res.json(),
)) as Partial<ServerMetadata>;
if (metadata.type !== "ServerMetadata") {
throw new Error("Invalid instance metadata");
}
if (metadata.type !== "ServerMetadata") {
throw new Error("Invalid instance metadata");
}
if (!(metadata.name && metadata.version)) {
throw new Error("Invalid instance metadata");
}
if (!(metadata.name && metadata.version)) {
throw new Error("Invalid instance metadata");
}
return await client.instance.create({
data: {
base_url: hostname,
name: metadata.name,
version: metadata.version,
logo: metadata.logo as any,
},
});
return await client.instance.create({
data: {
base_url: hostname,
name: metadata.name,
version: metadata.version,
logo: metadata.logo,
},
});
};

View file

@ -1,23 +1,25 @@
import type { Like, Prisma } from "@prisma/client";
import { config } from "config-manager";
import { client } from "~database/datasource";
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import type { Like as LysandLike } from "~types/lysand/Object";
import type { Like } from "@prisma/client";
import { client } from "~database/datasource";
import type { UserWithRelations } from "./User";
import type { StatusWithRelations } from "./Status";
import { config } from "config-manager";
import type { UserWithRelations } from "./User";
/**
* Represents a Like entity in the database.
*/
export const toLysand = (like: Like): LysandLike => {
return {
id: like.id,
author: (like as any).liker?.uri,
type: "Like",
created_at: new Date(like.createdAt).toISOString(),
object: (like as any).liked?.uri,
uri: `${config.http.base_url}/actions/${like.id}`,
};
return {
id: like.id,
// biome-ignore lint/suspicious/noExplicitAny: to be rewritten
author: (like as any).liker?.uri,
type: "Like",
created_at: new Date(like.createdAt).toISOString(),
// biome-ignore lint/suspicious/noExplicitAny: to be rewritten
object: (like as any).liked?.uri,
uri: `${config.http.base_url}/actions/${like.id}`,
};
};
/**
@ -26,29 +28,29 @@ export const toLysand = (like: Like): LysandLike => {
* @param status Status being liked
*/
export const createLike = async (
user: UserWithRelations,
status: StatusWithRelations
user: UserWithRelations,
status: StatusWithRelations,
) => {
await client.like.create({
data: {
likedId: status.id,
likerId: user.id,
},
});
await client.like.create({
data: {
likedId: status.id,
likerId: user.id,
},
});
if (status.author.instanceId === user.instanceId) {
// Notify the user that their post has been favourited
await client.notification.create({
data: {
accountId: user.id,
type: "favourite",
notifiedId: status.authorId,
statusId: status.id,
},
});
} else {
// TODO: Add database jobs for federating this
}
if (status.author.instanceId === user.instanceId) {
// Notify the user that their post has been favourited
await client.notification.create({
data: {
accountId: user.id,
type: "favourite",
notifiedId: status.authorId,
statusId: status.id,
},
});
} else {
// TODO: Add database jobs for federating this
}
};
/**
@ -57,28 +59,28 @@ export const createLike = async (
* @param status Status being unliked
*/
export const deleteLike = async (
user: UserWithRelations,
status: StatusWithRelations
user: UserWithRelations,
status: StatusWithRelations,
) => {
await client.like.deleteMany({
where: {
likedId: status.id,
likerId: user.id,
},
});
await client.like.deleteMany({
where: {
likedId: status.id,
likerId: user.id,
},
});
// Notify the user that their post has been favourited
await client.notification.deleteMany({
where: {
accountId: user.id,
type: "favourite",
notifiedId: status.authorId,
statusId: status.id,
},
});
// Notify the user that their post has been favourited
await client.notification.deleteMany({
where: {
accountId: user.id,
type: "favourite",
notifiedId: status.authorId,
statusId: status.id,
},
});
if (user.instanceId === null && status.author.instanceId !== null) {
// User is local, federate the delete
// TODO: Federate this
}
if (user.instanceId === null && status.author.instanceId !== null) {
// User is local, federate the delete
// TODO: Federate this
}
};

View file

@ -4,20 +4,20 @@ import { type StatusWithRelations, statusToAPI } from "./Status";
import { type UserWithRelations, userToAPI } from "./User";
export type NotificationWithRelations = Notification & {
status: StatusWithRelations | null;
account: UserWithRelations;
status: StatusWithRelations | null;
account: UserWithRelations;
};
export const notificationToAPI = async (
notification: NotificationWithRelations
notification: NotificationWithRelations,
): Promise<APINotification> => {
return {
account: userToAPI(notification.account),
created_at: new Date(notification.createdAt).toISOString(),
id: notification.id,
type: notification.type,
status: notification.status
? await statusToAPI(notification.status, notification.account)
: undefined,
};
return {
account: userToAPI(notification.account),
created_at: new Date(notification.createdAt).toISOString(),
id: notification.id,
type: notification.type,
status: notification.status
? await statusToAPI(notification.status, notification.account)
: undefined,
};
};

View file

@ -9,79 +9,79 @@ import type { LysandObjectType } from "~types/lysand/Object";
*/
export const createFromObject = async (object: LysandObjectType) => {
const foundObject = await client.lysandObject.findFirst({
where: { remote_id: object.id },
include: {
author: true,
},
});
const foundObject = await client.lysandObject.findFirst({
where: { remote_id: object.id },
include: {
author: true,
},
});
if (foundObject) {
return foundObject;
}
if (foundObject) {
return foundObject;
}
const author = await client.lysandObject.findFirst({
where: { uri: (object as any).author },
});
const author = await client.lysandObject.findFirst({
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
where: { uri: (object as any).author },
});
return await client.lysandObject.create({
data: {
authorId: author?.id,
created_at: new Date(object.created_at),
extensions: object.extensions || {},
remote_id: object.id,
type: object.type,
uri: object.uri,
// Rest of data (remove id, author, created_at, extensions, type, uri)
extra_data: Object.fromEntries(
Object.entries(object).filter(
([key]) =>
![
"id",
"author",
"created_at",
"extensions",
"type",
"uri",
].includes(key)
)
),
},
});
return await client.lysandObject.create({
data: {
authorId: author?.id,
created_at: new Date(object.created_at),
extensions: object.extensions || {},
remote_id: object.id,
type: object.type,
uri: object.uri,
// Rest of data (remove id, author, created_at, extensions, type, uri)
extra_data: Object.fromEntries(
Object.entries(object).filter(
([key]) =>
![
"id",
"author",
"created_at",
"extensions",
"type",
"uri",
].includes(key),
),
),
},
});
};
export const toLysand = (lyObject: LysandObject): LysandObjectType => {
return {
id: lyObject.remote_id || lyObject.id,
created_at: new Date(lyObject.created_at).toISOString(),
type: lyObject.type,
uri: lyObject.uri,
// @ts-expect-error This works, I promise
...lyObject.extra_data,
extensions: lyObject.extensions,
};
return {
id: lyObject.remote_id || lyObject.id,
created_at: new Date(lyObject.created_at).toISOString(),
type: lyObject.type,
uri: lyObject.uri,
...lyObject.extra_data,
extensions: lyObject.extensions,
};
};
export const isPublication = (lyObject: LysandObject): boolean => {
return lyObject.type === "Note" || lyObject.type === "Patch";
return lyObject.type === "Note" || lyObject.type === "Patch";
};
export const isAction = (lyObject: LysandObject): boolean => {
return [
"Like",
"Follow",
"Dislike",
"FollowAccept",
"FollowReject",
"Undo",
"Announce",
].includes(lyObject.type);
return [
"Like",
"Follow",
"Dislike",
"FollowAccept",
"FollowReject",
"Undo",
"Announce",
].includes(lyObject.type);
};
export const isActor = (lyObject: LysandObject): boolean => {
return lyObject.type === "User";
return lyObject.type === "User";
};
export const isExtension = (lyObject: LysandObject): boolean => {
return lyObject.type === "Extension";
return lyObject.type === "Extension";
};

View file

@ -1,7 +1,7 @@
// import { Worker } from "bullmq";
import { statusToLysand, type StatusWithRelations } from "./Status";
import type { User } from "@prisma/client";
import { config } from "config-manager";
// import { Worker } from "bullmq";
import { type StatusWithRelations, statusToLysand } from "./Status";
/* export const federationWorker = new Worker(
"federation",
@ -123,68 +123,68 @@ import { config } from "config-manager";
* from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
*/
export const str2ab = (str: string) => {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
};
export const federateStatusTo = async (
status: StatusWithRelations,
sender: User,
user: User
status: StatusWithRelations,
sender: User,
user: User,
) => {
const privateKey = await crypto.subtle.importKey(
"pkcs8",
str2ab(atob(user.privateKey ?? "")),
"Ed25519",
false,
["sign"]
);
const privateKey = await crypto.subtle.importKey(
"pkcs8",
str2ab(atob(user.privateKey ?? "")),
"Ed25519",
false,
["sign"],
);
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode("request_body")
);
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode("request_body"),
);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const userInbox = new URL(user.endpoints.inbox);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const userInbox = new URL(user.endpoints.inbox);
const date = new Date();
const date = new Date();
const signature = await crypto.subtle.sign(
"Ed25519",
privateKey,
new TextEncoder().encode(
`(request-target): post ${userInbox.pathname}\n` +
`host: ${userInbox.host}\n` +
`date: ${date.toUTCString()}\n` +
`digest: SHA-256=${btoa(
String.fromCharCode(...new Uint8Array(digest))
)}\n`
)
);
const signature = await crypto.subtle.sign(
"Ed25519",
privateKey,
new TextEncoder().encode(
`(request-target): post ${userInbox.pathname}\n` +
`host: ${userInbox.host}\n` +
`date: ${date.toUTCString()}\n` +
`digest: SHA-256=${btoa(
String.fromCharCode(...new Uint8Array(digest)),
)}\n`,
),
);
const signatureBase64 = btoa(
String.fromCharCode(...new Uint8Array(signature))
);
const signatureBase64 = btoa(
String.fromCharCode(...new Uint8Array(signature)),
);
return fetch(userInbox, {
method: "POST",
headers: {
"Content-Type": "application/json",
Date: date.toUTCString(),
Origin: config.http.base_url,
Signature: `keyId="${sender.uri}",algorithm="ed25519",headers="(request-target) host date digest",signature="${signatureBase64}"`,
},
body: JSON.stringify(statusToLysand(status)),
});
return fetch(userInbox, {
method: "POST",
headers: {
"Content-Type": "application/json",
Date: date.toUTCString(),
Origin: config.http.base_url,
Signature: `keyId="${sender.uri}",algorithm="ed25519",headers="(request-target) host date digest",signature="${signatureBase64}"`,
},
body: JSON.stringify(statusToLysand(status)),
});
};
export const addStatusFederationJob = async (statusId: string) => {
/* await federationQueue.add("federation", {
/* await federationQueue.add("federation", {
id: statusId,
}); */
};

View file

@ -1,6 +1,6 @@
import type { Relationship, User } from "@prisma/client";
import type { APIRelationship } from "~types/entities/relationship";
import { client } from "~database/datasource";
import type { APIRelationship } from "~types/entities/relationship";
/**
* Stores Mastodon API relationships
@ -13,55 +13,55 @@ import { client } from "~database/datasource";
* @returns The newly created relationship.
*/
export const createNewRelationship = async (
owner: User,
other: User
owner: User,
other: User,
): Promise<Relationship> => {
return await client.relationship.create({
data: {
ownerId: owner.id,
subjectId: other.id,
languages: [],
following: false,
showingReblogs: false,
notifying: false,
followedBy: false,
blocking: false,
blockedBy: false,
muting: false,
mutingNotifications: false,
requested: false,
domainBlocking: false,
endorsed: false,
note: "",
},
});
return await client.relationship.create({
data: {
ownerId: owner.id,
subjectId: other.id,
languages: [],
following: false,
showingReblogs: false,
notifying: false,
followedBy: false,
blocking: false,
blockedBy: false,
muting: false,
mutingNotifications: false,
requested: false,
domainBlocking: false,
endorsed: false,
note: "",
},
});
};
export const checkForBidirectionalRelationships = async (
user1: User,
user2: User,
createIfNotExists = true
user1: User,
user2: User,
createIfNotExists = true,
): Promise<boolean> => {
const relationship1 = await client.relationship.findFirst({
where: {
ownerId: user1.id,
subjectId: user2.id,
},
});
const relationship1 = await client.relationship.findFirst({
where: {
ownerId: user1.id,
subjectId: user2.id,
},
});
const relationship2 = await client.relationship.findFirst({
where: {
ownerId: user2.id,
subjectId: user1.id,
},
});
const relationship2 = await client.relationship.findFirst({
where: {
ownerId: user2.id,
subjectId: user1.id,
},
});
if (!relationship1 && !relationship2 && createIfNotExists) {
await createNewRelationship(user1, user2);
await createNewRelationship(user2, user1);
}
if (!relationship1 && !relationship2 && createIfNotExists) {
await createNewRelationship(user1, user2);
await createNewRelationship(user2, user1);
}
return !!relationship1 && !!relationship2;
return !!relationship1 && !!relationship2;
};
/**
@ -69,20 +69,20 @@ export const checkForBidirectionalRelationships = async (
* @returns The API-friendly relationship.
*/
export const relationshipToAPI = (rel: Relationship): APIRelationship => {
return {
blocked_by: rel.blockedBy,
blocking: rel.blocking,
domain_blocking: rel.domainBlocking,
endorsed: rel.endorsed,
followed_by: rel.followedBy,
following: rel.following,
id: rel.subjectId,
muting: rel.muting,
muting_notifications: rel.mutingNotifications,
notifying: rel.notifying,
requested: rel.requested,
showing_reblogs: rel.showingReblogs,
languages: rel.languages,
note: rel.note,
};
return {
blocked_by: rel.blockedBy,
blocking: rel.blocking,
domain_blocking: rel.domainBlocking,
endorsed: rel.endorsed,
followed_by: rel.followedBy,
following: rel.following,
id: rel.subjectId,
muting: rel.muting,
muting_notifications: rel.mutingNotifications,
notifying: rel.notifying,
requested: rel.requested,
showing_reblogs: rel.showingReblogs,
languages: rel.languages,
note: rel.note,
};
};

View file

@ -1,37 +1,37 @@
import { getBestContentType } from "@content_types";
import { addStausToMeilisearch } from "@meilisearch";
import {
type Application,
type Emoji,
Prisma,
type Relationship,
type Status,
type User,
} from "@prisma/client";
import { sanitizeHtml } from "@sanitization";
import { config } from "config-manager";
import { htmlToText } from "html-to-text";
import linkifyHtml from "linkify-html";
import linkifyStr from "linkify-string";
import { parse } from "marked";
import { client } from "~database/datasource";
import type { APIAttachment } from "~types/entities/attachment";
import type { APIStatus } from "~types/entities/status";
import type { LysandPublication, Note } from "~types/lysand/Object";
import { applicationToAPI } from "./Application";
import { attachmentToAPI } from "./Attachment";
import { emojiToAPI, emojiToLysand, parseEmojis } from "./Emoji";
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import type { UserWithRelations } from "./User";
import { fetchRemoteUser, parseMentionsUris, userToAPI } from "./User";
import { client } from "~database/datasource";
import type { LysandPublication, Note } from "~types/lysand/Object";
import { htmlToText } from "html-to-text";
import { getBestContentType } from "@content_types";
import {
Prisma,
type Application,
type Emoji,
type Relationship,
type Status,
type User,
} from "@prisma/client";
import { emojiToAPI, emojiToLysand, parseEmojis } from "./Emoji";
import type { APIStatus } from "~types/entities/status";
import { applicationToAPI } from "./Application";
import { attachmentToAPI } from "./Attachment";
import type { APIAttachment } from "~types/entities/attachment";
import { sanitizeHtml } from "@sanitization";
import { parse } from "marked";
import linkifyStr from "linkify-string";
import linkifyHtml from "linkify-html";
import { addStausToMeilisearch } from "@meilisearch";
import { config } from "config-manager";
import { statusAndUserRelations, userRelations } from "./relations";
const statusRelations = Prisma.validator<Prisma.StatusDefaultArgs>()({
include: statusAndUserRelations,
include: statusAndUserRelations,
});
export type StatusWithRelations = Prisma.StatusGetPayload<
typeof statusRelations
typeof statusRelations
>;
/**
@ -44,76 +44,75 @@ export type StatusWithRelations = Prisma.StatusGetPayload<
* @returns Whether this status is viewable by the user.
*/
export const isViewableByUser = (status: Status, user: User | null) => {
if (status.authorId === user?.id) return true;
if (status.visibility === "public") return true;
else if (status.visibility === "unlisted") return true;
else if (status.visibility === "private") {
// @ts-expect-error Prisma TypeScript types dont include relations
return !!(user?.relationships as Relationship[]).find(
rel => rel.id === status.authorId
);
} else {
// @ts-expect-error Prisma TypeScript types dont include relations
return user && (status.mentions as User[]).includes(user);
}
if (status.authorId === user?.id) return true;
if (status.visibility === "public") return true;
if (status.visibility === "unlisted") return true;
if (status.visibility === "private") {
// @ts-expect-error Prisma TypeScript types dont include relations
return !!(user?.relationships as Relationship[]).find(
(rel) => rel.id === status.authorId,
);
}
// @ts-expect-error Prisma TypeScript types dont include relations
return user && (status.mentions as User[]).includes(user);
};
export const fetchFromRemote = async (uri: string): Promise<Status | null> => {
// Check if already in database
// Check if already in database
const existingStatus: StatusWithRelations | null =
await client.status.findFirst({
where: {
uri: uri,
},
include: statusAndUserRelations,
});
const existingStatus: StatusWithRelations | null =
await client.status.findFirst({
where: {
uri: uri,
},
include: statusAndUserRelations,
});
if (existingStatus) return existingStatus;
if (existingStatus) return existingStatus;
const status = await fetch(uri);
const status = await fetch(uri);
if (status.status === 404) return null;
if (status.status === 404) return null;
const body = (await status.json()) as LysandPublication;
const body = (await status.json()) as LysandPublication;
const content = getBestContentType(body.contents);
const content = getBestContentType(body.contents);
const emojis = await parseEmojis(content?.content || "");
const emojis = await parseEmojis(content?.content || "");
const author = await fetchRemoteUser(body.author);
const author = await fetchRemoteUser(body.author);
let replyStatus: Status | null = null;
let quotingStatus: Status | null = null;
let replyStatus: Status | null = null;
let quotingStatus: Status | null = null;
if (body.replies_to.length > 0) {
replyStatus = await fetchFromRemote(body.replies_to[0]);
}
if (body.replies_to.length > 0) {
replyStatus = await fetchFromRemote(body.replies_to[0]);
}
if (body.quotes.length > 0) {
quotingStatus = await fetchFromRemote(body.quotes[0]);
}
if (body.quotes.length > 0) {
quotingStatus = await fetchFromRemote(body.quotes[0]);
}
return await createNewStatus({
account: author,
content: content?.content || "",
content_type: content?.content_type,
application: null,
// TODO: Add visibility
visibility: "public",
spoiler_text: body.subject || "",
uri: body.uri,
sensitive: body.is_sensitive,
emojis: emojis,
mentions: await parseMentionsUris(body.mentions),
reply: replyStatus
? {
status: replyStatus,
user: (replyStatus as any).author,
}
: undefined,
quote: quotingStatus || undefined,
});
return await createNewStatus({
account: author,
content: content?.content || "",
content_type: content?.content_type,
application: null,
// TODO: Add visibility
visibility: "public",
spoiler_text: body.subject || "",
uri: body.uri,
sensitive: body.is_sensitive,
emojis: emojis,
mentions: await parseMentionsUris(body.mentions),
reply: replyStatus
? {
status: replyStatus,
user: (replyStatus as StatusWithRelations).author,
}
: undefined,
quote: quotingStatus || undefined,
});
};
/**
@ -121,34 +120,34 @@ export const fetchFromRemote = async (uri: string): Promise<Status | null> => {
*/
// eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars
export const getAncestors = async (
status: StatusWithRelations,
fetcher: UserWithRelations | null
status: StatusWithRelations,
fetcher: UserWithRelations | null,
) => {
const ancestors: StatusWithRelations[] = [];
const ancestors: StatusWithRelations[] = [];
let currentStatus = status;
let currentStatus = status;
while (currentStatus.inReplyToPostId) {
const parent = await client.status.findFirst({
where: {
id: currentStatus.inReplyToPostId,
},
include: statusAndUserRelations,
});
while (currentStatus.inReplyToPostId) {
const parent = await client.status.findFirst({
where: {
id: currentStatus.inReplyToPostId,
},
include: statusAndUserRelations,
});
if (!parent) break;
if (!parent) break;
ancestors.push(parent);
ancestors.push(parent);
currentStatus = parent;
}
currentStatus = parent;
}
// Filter for posts that are viewable by the user
// Filter for posts that are viewable by the user
const viewableAncestors = ancestors.filter(ancestor =>
isViewableByUser(ancestor, fetcher)
);
return viewableAncestors;
const viewableAncestors = ancestors.filter((ancestor) =>
isViewableByUser(ancestor, fetcher),
);
return viewableAncestors;
};
/**
@ -157,42 +156,42 @@ export const getAncestors = async (
*/
// eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars
export const getDescendants = async (
status: StatusWithRelations,
fetcher: UserWithRelations | null,
depth = 0
status: StatusWithRelations,
fetcher: UserWithRelations | null,
depth = 0,
) => {
const descendants: StatusWithRelations[] = [];
const descendants: StatusWithRelations[] = [];
const currentStatus = status;
const currentStatus = status;
// Fetch all children of children of children recursively calling getDescendants
// Fetch all children of children of children recursively calling getDescendants
const children = await client.status.findMany({
where: {
inReplyToPostId: currentStatus.id,
},
include: statusAndUserRelations,
});
const children = await client.status.findMany({
where: {
inReplyToPostId: currentStatus.id,
},
include: statusAndUserRelations,
});
for (const child of children) {
descendants.push(child);
for (const child of children) {
descendants.push(child);
if (depth < 20) {
const childDescendants = await getDescendants(
child,
fetcher,
depth + 1
);
descendants.push(...childDescendants);
}
}
if (depth < 20) {
const childDescendants = await getDescendants(
child,
fetcher,
depth + 1,
);
descendants.push(...childDescendants);
}
}
// Filter for posts that are viewable by the user
// Filter for posts that are viewable by the user
const viewableDescendants = descendants.filter(descendant =>
isViewableByUser(descendant, fetcher)
);
return viewableDescendants;
const viewableDescendants = descendants.filter((descendant) =>
isViewableByUser(descendant, fetcher),
);
return viewableDescendants;
};
/**
@ -201,250 +200,250 @@ export const getDescendants = async (
* @returns A promise that resolves with the new status.
*/
export const createNewStatus = async (data: {
account: User;
application: Application | null;
content: string;
visibility: APIStatus["visibility"];
sensitive: boolean;
spoiler_text: string;
emojis?: Emoji[];
content_type?: string;
uri?: string;
mentions?: User[];
media_attachments?: string[];
reply?: {
status: Status;
user: User;
};
quote?: Status;
account: User;
application: Application | null;
content: string;
visibility: APIStatus["visibility"];
sensitive: boolean;
spoiler_text: string;
emojis?: Emoji[];
content_type?: string;
uri?: string;
mentions?: User[];
media_attachments?: string[];
reply?: {
status: Status;
user: User;
};
quote?: Status;
}) => {
// Get people mentioned in the content (match @username or @username@domain.com mentions)
const mentionedPeople =
data.content.match(/@[a-zA-Z0-9_]+(@[a-zA-Z0-9_]+)?/g) ?? [];
// Get people mentioned in the content (match @username or @username@domain.com mentions)
const mentionedPeople =
data.content.match(/@[a-zA-Z0-9_]+(@[a-zA-Z0-9_]+)?/g) ?? [];
let mentions = data.mentions || [];
let mentions = data.mentions || [];
// Parse emojis
const emojis = await parseEmojis(data.content);
// Parse emojis
const emojis = await parseEmojis(data.content);
data.emojis = data.emojis ? [...data.emojis, ...emojis] : emojis;
data.emojis = data.emojis ? [...data.emojis, ...emojis] : emojis;
// Get list of mentioned users
if (mentions.length === 0) {
mentions = await client.user.findMany({
where: {
OR: mentionedPeople.map(person => ({
username: person.split("@")[1],
instance: {
base_url: person.split("@")[2],
},
})),
},
include: userRelations,
});
}
// Get list of mentioned users
if (mentions.length === 0) {
mentions = await client.user.findMany({
where: {
OR: mentionedPeople.map((person) => ({
username: person.split("@")[1],
instance: {
base_url: person.split("@")[2],
},
})),
},
include: userRelations,
});
}
let formattedContent;
let formattedContent = "";
// Get HTML version of content
if (data.content_type === "text/markdown") {
formattedContent = linkifyHtml(
await sanitizeHtml(await parse(data.content))
);
} else if (data.content_type === "text/x.misskeymarkdown") {
// Parse as MFM
} else {
// Parse as plaintext
formattedContent = linkifyStr(data.content);
// Get HTML version of content
if (data.content_type === "text/markdown") {
formattedContent = linkifyHtml(
await sanitizeHtml(await parse(data.content)),
);
} else if (data.content_type === "text/x.misskeymarkdown") {
// Parse as MFM
} else {
// Parse as plaintext
formattedContent = linkifyStr(data.content);
// Split by newline and add <p> tags
formattedContent = formattedContent
.split("\n")
.map(line => `<p>${line}</p>`)
.join("\n");
}
// Split by newline and add <p> tags
formattedContent = formattedContent
.split("\n")
.map((line) => `<p>${line}</p>`)
.join("\n");
}
let status = await client.status.create({
data: {
authorId: data.account.id,
applicationId: data.application?.id,
content: formattedContent,
contentSource: data.content,
contentType: data.content_type,
visibility: data.visibility,
sensitive: data.sensitive,
spoilerText: data.spoiler_text,
emojis: {
connect: data.emojis.map(emoji => {
return {
id: emoji.id,
};
}),
},
attachments: data.media_attachments
? {
connect: data.media_attachments.map(attachment => {
return {
id: attachment,
};
}),
}
: undefined,
inReplyToPostId: data.reply?.status.id,
quotingPostId: data.quote?.id,
instanceId: data.account.instanceId || undefined,
isReblog: false,
uri:
data.uri ||
`${config.http.base_url}/statuses/FAKE-${crypto.randomUUID()}`,
mentions: {
connect: mentions.map(mention => {
return {
id: mention.id,
};
}),
},
},
include: statusAndUserRelations,
});
let status = await client.status.create({
data: {
authorId: data.account.id,
applicationId: data.application?.id,
content: formattedContent,
contentSource: data.content,
contentType: data.content_type,
visibility: data.visibility,
sensitive: data.sensitive,
spoilerText: data.spoiler_text,
emojis: {
connect: data.emojis.map((emoji) => {
return {
id: emoji.id,
};
}),
},
attachments: data.media_attachments
? {
connect: data.media_attachments.map((attachment) => {
return {
id: attachment,
};
}),
}
: undefined,
inReplyToPostId: data.reply?.status.id,
quotingPostId: data.quote?.id,
instanceId: data.account.instanceId || undefined,
isReblog: false,
uri:
data.uri ||
`${config.http.base_url}/statuses/FAKE-${crypto.randomUUID()}`,
mentions: {
connect: mentions.map((mention) => {
return {
id: mention.id,
};
}),
},
},
include: statusAndUserRelations,
});
// Update URI
status = await client.status.update({
where: {
id: status.id,
},
data: {
uri: data.uri || `${config.http.base_url}/statuses/${status.id}`,
},
include: statusAndUserRelations,
});
// Update URI
status = await client.status.update({
where: {
id: status.id,
},
data: {
uri: data.uri || `${config.http.base_url}/statuses/${status.id}`,
},
include: statusAndUserRelations,
});
// Create notification
if (status.inReplyToPost) {
await client.notification.create({
data: {
notifiedId: status.inReplyToPost.authorId,
accountId: status.authorId,
type: "mention",
statusId: status.id,
},
});
}
// Create notification
if (status.inReplyToPost) {
await client.notification.create({
data: {
notifiedId: status.inReplyToPost.authorId,
accountId: status.authorId,
type: "mention",
statusId: status.id,
},
});
}
// Add to search index
await addStausToMeilisearch(status);
// Add to search index
await addStausToMeilisearch(status);
return status;
return status;
};
export const editStatus = async (
status: StatusWithRelations,
data: {
content: string;
visibility?: APIStatus["visibility"];
sensitive: boolean;
spoiler_text: string;
emojis?: Emoji[];
content_type?: string;
uri?: string;
mentions?: User[];
media_attachments?: string[];
}
status: StatusWithRelations,
data: {
content: string;
visibility?: APIStatus["visibility"];
sensitive: boolean;
spoiler_text: string;
emojis?: Emoji[];
content_type?: string;
uri?: string;
mentions?: User[];
media_attachments?: string[];
},
) => {
// Get people mentioned in the content (match @username or @username@domain.com mentions
const mentionedPeople =
data.content.match(/@[a-zA-Z0-9_]+(@[a-zA-Z0-9_]+)?/g) ?? [];
// Get people mentioned in the content (match @username or @username@domain.com mentions
const mentionedPeople =
data.content.match(/@[a-zA-Z0-9_]+(@[a-zA-Z0-9_]+)?/g) ?? [];
let mentions = data.mentions || [];
let mentions = data.mentions || [];
// Parse emojis
const emojis = await parseEmojis(data.content);
// Parse emojis
const emojis = await parseEmojis(data.content);
data.emojis = data.emojis ? [...data.emojis, ...emojis] : emojis;
data.emojis = data.emojis ? [...data.emojis, ...emojis] : emojis;
// Get list of mentioned users
if (mentions.length === 0) {
mentions = await client.user.findMany({
where: {
OR: mentionedPeople.map(person => ({
username: person.split("@")[1],
instance: {
base_url: person.split("@")[2],
},
})),
},
include: userRelations,
});
}
// Get list of mentioned users
if (mentions.length === 0) {
mentions = await client.user.findMany({
where: {
OR: mentionedPeople.map((person) => ({
username: person.split("@")[1],
instance: {
base_url: person.split("@")[2],
},
})),
},
include: userRelations,
});
}
let formattedContent;
let formattedContent = "";
// Get HTML version of content
if (data.content_type === "text/markdown") {
formattedContent = linkifyHtml(
await sanitizeHtml(await parse(data.content))
);
} else if (data.content_type === "text/x.misskeymarkdown") {
// Parse as MFM
} else {
// Parse as plaintext
formattedContent = linkifyStr(data.content);
// Get HTML version of content
if (data.content_type === "text/markdown") {
formattedContent = linkifyHtml(
await sanitizeHtml(await parse(data.content)),
);
} else if (data.content_type === "text/x.misskeymarkdown") {
// Parse as MFM
} else {
// Parse as plaintext
formattedContent = linkifyStr(data.content);
// Split by newline and add <p> tags
formattedContent = formattedContent
.split("\n")
.map(line => `<p>${line}</p>`)
.join("\n");
}
// Split by newline and add <p> tags
formattedContent = formattedContent
.split("\n")
.map((line) => `<p>${line}</p>`)
.join("\n");
}
const newStatus = await client.status.update({
where: {
id: status.id,
},
data: {
content: formattedContent,
contentSource: data.content,
contentType: data.content_type,
visibility: data.visibility,
sensitive: data.sensitive,
spoilerText: data.spoiler_text,
emojis: {
connect: data.emojis.map(emoji => {
return {
id: emoji.id,
};
}),
},
attachments: data.media_attachments
? {
connect: data.media_attachments.map(attachment => {
return {
id: attachment,
};
}),
}
: undefined,
mentions: {
connect: mentions.map(mention => {
return {
id: mention.id,
};
}),
},
},
include: statusAndUserRelations,
});
const newStatus = await client.status.update({
where: {
id: status.id,
},
data: {
content: formattedContent,
contentSource: data.content,
contentType: data.content_type,
visibility: data.visibility,
sensitive: data.sensitive,
spoilerText: data.spoiler_text,
emojis: {
connect: data.emojis.map((emoji) => {
return {
id: emoji.id,
};
}),
},
attachments: data.media_attachments
? {
connect: data.media_attachments.map((attachment) => {
return {
id: attachment,
};
}),
}
: undefined,
mentions: {
connect: mentions.map((mention) => {
return {
id: mention.id,
};
}),
},
},
include: statusAndUserRelations,
});
return newStatus;
return newStatus;
};
export const isFavouritedBy = async (status: Status, user: User) => {
return !!(await client.like.findFirst({
where: {
likerId: user.id,
likedId: status.id,
},
}));
return !!(await client.like.findFirst({
where: {
likerId: user.id,
likedId: status.id,
},
}));
};
/**
@ -452,67 +451,67 @@ export const isFavouritedBy = async (status: Status, user: User) => {
* @returns A promise that resolves with the API status.
*/
export const statusToAPI = async (
status: StatusWithRelations,
user?: UserWithRelations
status: StatusWithRelations,
user?: UserWithRelations,
): Promise<APIStatus> => {
return {
id: status.id,
in_reply_to_id: status.inReplyToPostId || null,
in_reply_to_account_id: status.inReplyToPost?.authorId || null,
// @ts-expect-error Prisma TypeScript types dont include relations
account: userToAPI(status.author),
created_at: new Date(status.createdAt).toISOString(),
application: status.application
? applicationToAPI(status.application)
: null,
card: null,
content: status.content,
emojis: status.emojis.map(emoji => emojiToAPI(emoji)),
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
favourited: !!(status.likes ?? []).find(
like => like.likerId === user?.id
),
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
favourites_count: (status.likes ?? []).length,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
media_attachments: (status.attachments ?? []).map(
a => attachmentToAPI(a) as APIAttachment
),
// @ts-expect-error Prisma TypeScript types dont include relations
mentions: status.mentions.map(mention => userToAPI(mention)),
language: null,
muted: user
? user.relationships.find(r => r.subjectId == status.authorId)
?.muting || false
: false,
pinned: status.pinnedBy.find(u => u.id === user?.id) ? true : false,
// TODO: Add pols
poll: null,
reblog: status.reblog
? await statusToAPI(status.reblog as unknown as StatusWithRelations)
: null,
reblogged: !!(await client.status.findFirst({
where: {
authorId: user?.id,
reblogId: status.id,
},
})),
reblogs_count: status._count.reblogs,
replies_count: status._count.replies,
sensitive: status.sensitive,
spoiler_text: status.spoilerText,
tags: [],
uri: `${config.http.base_url}/statuses/${status.id}`,
visibility: "public",
url: `${config.http.base_url}/statuses/${status.id}`,
bookmarked: false,
quote: status.quotingPost
? await statusToAPI(
status.quotingPost as unknown as StatusWithRelations
)
: null,
quote_id: status.quotingPost?.id || undefined,
};
return {
id: status.id,
in_reply_to_id: status.inReplyToPostId || null,
in_reply_to_account_id: status.inReplyToPost?.authorId || null,
// @ts-expect-error Prisma TypeScript types dont include relations
account: userToAPI(status.author),
created_at: new Date(status.createdAt).toISOString(),
application: status.application
? applicationToAPI(status.application)
: null,
card: null,
content: status.content,
emojis: status.emojis.map((emoji) => emojiToAPI(emoji)),
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
favourited: !!(status.likes ?? []).find(
(like) => like.likerId === user?.id,
),
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
favourites_count: (status.likes ?? []).length,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
media_attachments: (status.attachments ?? []).map(
(a) => attachmentToAPI(a) as APIAttachment,
),
// @ts-expect-error Prisma TypeScript types dont include relations
mentions: status.mentions.map((mention) => userToAPI(mention)),
language: null,
muted: user
? user.relationships.find((r) => r.subjectId === status.authorId)
?.muting || false
: false,
pinned: status.pinnedBy.find((u) => u.id === user?.id) ? true : false,
// TODO: Add pols
poll: null,
reblog: status.reblog
? await statusToAPI(status.reblog as unknown as StatusWithRelations)
: null,
reblogged: !!(await client.status.findFirst({
where: {
authorId: user?.id,
reblogId: status.id,
},
})),
reblogs_count: status._count.reblogs,
replies_count: status._count.replies,
sensitive: status.sensitive,
spoiler_text: status.spoilerText,
tags: [],
uri: `${config.http.base_url}/statuses/${status.id}`,
visibility: "public",
url: `${config.http.base_url}/statuses/${status.id}`,
bookmarked: false,
quote: status.quotingPost
? await statusToAPI(
status.quotingPost as unknown as StatusWithRelations,
)
: null,
quote_id: status.quotingPost?.id || undefined,
};
};
/* export const statusToActivityPub = async (
@ -563,35 +562,35 @@ export const statusToAPI = async (
}; */
export const statusToLysand = (status: StatusWithRelations): Note => {
return {
type: "Note",
created_at: new Date(status.createdAt).toISOString(),
id: status.id,
author: status.authorId,
uri: `${config.http.base_url}/users/${status.authorId}/statuses/${status.id}`,
contents: [
{
content: status.content,
content_type: "text/html",
},
{
// Content converted to plaintext
content: htmlToText(status.content),
content_type: "text/plain",
},
],
// TODO: Add attachments
attachments: [],
is_sensitive: status.sensitive,
mentions: status.mentions.map(mention => mention.uri),
quotes: status.quotingPost ? [status.quotingPost.uri] : [],
replies_to: status.inReplyToPostId ? [status.inReplyToPostId] : [],
subject: status.spoilerText,
extensions: {
"org.lysand:custom_emojis": {
emojis: status.emojis.map(emoji => emojiToLysand(emoji)),
},
// TODO: Add polls and reactions
},
};
return {
type: "Note",
created_at: new Date(status.createdAt).toISOString(),
id: status.id,
author: status.authorId,
uri: `${config.http.base_url}/users/${status.authorId}/statuses/${status.id}`,
contents: [
{
content: status.content,
content_type: "text/html",
},
{
// Content converted to plaintext
content: htmlToText(status.content),
content_type: "text/plain",
},
],
// TODO: Add attachments
attachments: [],
is_sensitive: status.sensitive,
mentions: status.mentions.map((mention) => mention.uri),
quotes: status.quotingPost ? [status.quotingPost.uri] : [],
replies_to: status.inReplyToPostId ? [status.inReplyToPostId] : [],
subject: status.spoilerText,
extensions: {
"org.lysand:custom_emojis": {
emojis: status.emojis.map((emoji) => emojiToLysand(emoji)),
},
// TODO: Add polls and reactions
},
};
};

View file

@ -2,5 +2,5 @@
* The type of token.
*/
export enum TokenType {
BEARER = "Bearer",
BEARER = "Bearer",
}

View file

@ -1,20 +1,20 @@
import type { APIAccount } from "~types/entities/account";
import type { LysandUser } from "~types/lysand/Object";
import { htmlToText } from "html-to-text";
import { addUserToMeilisearch } from "@meilisearch";
import type { User } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { type Config, config } from "config-manager";
import { htmlToText } from "html-to-text";
import { client } from "~database/datasource";
import { MediaBackendType } from "~packages/media-manager";
import type { APIAccount } from "~types/entities/account";
import type { APISource } from "~types/entities/source";
import type { LysandUser } from "~types/lysand/Object";
import { addEmojiIfNotExists, emojiToAPI, emojiToLysand } from "./Emoji";
import { addInstanceIfNotExists } from "./Instance";
import type { APISource } from "~types/entities/source";
import { addUserToMeilisearch } from "@meilisearch";
import { config, type Config } from "config-manager";
import { userRelations } from "./relations";
import { MediaBackendType } from "~packages/media-manager";
export interface AuthData {
user: UserWithRelations | null;
token: string;
user: UserWithRelations | null;
token: string;
}
/**
@ -23,7 +23,7 @@ export interface AuthData {
*/
const userRelations2 = Prisma.validator<Prisma.UserDefaultArgs>()({
include: userRelations,
include: userRelations,
});
export type UserWithRelations = Prisma.UserGetPayload<typeof userRelations2>;
@ -34,14 +34,15 @@ export type UserWithRelations = Prisma.UserGetPayload<typeof userRelations2>;
* @returns The raw URL for the user's avatar
*/
export const getAvatarUrl = (user: User, config: Config) => {
if (!user.avatar) return config.defaults.avatar;
if (config.media.backend === MediaBackendType.LOCAL) {
return `${config.http.base_url}/media/${user.avatar}`;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
} else if (config.media.backend === MediaBackendType.S3) {
return `${config.s3.public_url}/${user.avatar}`;
}
return "";
if (!user.avatar) return config.defaults.avatar;
if (config.media.backend === MediaBackendType.LOCAL) {
return `${config.http.base_url}/media/${user.avatar}`;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
}
if (config.media.backend === MediaBackendType.S3) {
return `${config.s3.public_url}/${user.avatar}`;
}
return "";
};
/**
@ -50,128 +51,129 @@ export const getAvatarUrl = (user: User, config: Config) => {
* @returns The raw URL for the user's header
*/
export const getHeaderUrl = (user: User, config: Config) => {
if (!user.header) return config.defaults.header;
if (config.media.backend === MediaBackendType.LOCAL) {
return `${config.http.base_url}/media/${user.header}`;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
} else if (config.media.backend === MediaBackendType.S3) {
return `${config.s3.public_url}/${user.header}`;
}
return "";
if (!user.header) return config.defaults.header;
if (config.media.backend === MediaBackendType.LOCAL) {
return `${config.http.base_url}/media/${user.header}`;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
}
if (config.media.backend === MediaBackendType.S3) {
return `${config.s3.public_url}/${user.header}`;
}
return "";
};
export const getFromRequest = async (req: Request): Promise<AuthData> => {
// Check auth token
const token = req.headers.get("Authorization")?.split(" ")[1] || "";
// Check auth token
const token = req.headers.get("Authorization")?.split(" ")[1] || "";
return { user: await retrieveUserFromToken(token), token };
return { user: await retrieveUserFromToken(token), token };
};
export const fetchRemoteUser = async (uri: string) => {
// Check if user not already in database
const foundUser = await client.user.findUnique({
where: {
uri,
},
include: userRelations,
});
// Check if user not already in database
const foundUser = await client.user.findUnique({
where: {
uri,
},
include: userRelations,
});
if (foundUser) return foundUser;
if (foundUser) return foundUser;
const response = await fetch(uri, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const response = await fetch(uri, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const data = (await response.json()) as Partial<LysandUser>;
const data = (await response.json()) as Partial<LysandUser>;
if (
!(
data.id &&
data.username &&
data.uri &&
data.created_at &&
data.disliked &&
data.featured &&
data.liked &&
data.followers &&
data.following &&
data.inbox &&
data.outbox &&
data.public_key
)
) {
throw new Error("Invalid user data");
}
if (
!(
data.id &&
data.username &&
data.uri &&
data.created_at &&
data.disliked &&
data.featured &&
data.liked &&
data.followers &&
data.following &&
data.inbox &&
data.outbox &&
data.public_key
)
) {
throw new Error("Invalid user data");
}
// Parse emojis and add them to database
const userEmojis =
data.extensions?.["org.lysand:custom_emojis"]?.emojis ?? [];
// Parse emojis and add them to database
const userEmojis =
data.extensions?.["org.lysand:custom_emojis"]?.emojis ?? [];
const user = await client.user.create({
data: {
username: data.username,
uri: data.uri,
createdAt: new Date(data.created_at),
endpoints: {
disliked: data.disliked,
featured: data.featured,
liked: data.liked,
followers: data.followers,
following: data.following,
inbox: data.inbox,
outbox: data.outbox,
},
avatar: (data.avatar && data.avatar[0].content) || "",
header: (data.header && data.header[0].content) || "",
displayName: data.display_name ?? "",
note: data.bio?.[0].content ?? "",
publicKey: data.public_key.public_key,
source: {
language: null,
note: "",
privacy: "public",
sensitive: false,
fields: [],
},
},
});
const user = await client.user.create({
data: {
username: data.username,
uri: data.uri,
createdAt: new Date(data.created_at),
endpoints: {
disliked: data.disliked,
featured: data.featured,
liked: data.liked,
followers: data.followers,
following: data.following,
inbox: data.inbox,
outbox: data.outbox,
},
avatar: data.avatar?.[0].content || "",
header: data.header?.[0].content || "",
displayName: data.display_name ?? "",
note: data.bio?.[0].content ?? "",
publicKey: data.public_key.public_key,
source: {
language: null,
note: "",
privacy: "public",
sensitive: false,
fields: [],
},
},
});
// Add to Meilisearch
await addUserToMeilisearch(user);
// Add to Meilisearch
await addUserToMeilisearch(user);
const emojis = [];
const emojis = [];
for (const emoji of userEmojis) {
emojis.push(await addEmojiIfNotExists(emoji));
}
for (const emoji of userEmojis) {
emojis.push(await addEmojiIfNotExists(emoji));
}
const uriData = new URL(data.uri);
const uriData = new URL(data.uri);
return await client.user.update({
where: {
id: user.id,
},
data: {
emojis: {
connect: emojis.map(emoji => ({
id: emoji.id,
})),
},
instanceId: (await addInstanceIfNotExists(uriData.origin)).id,
},
include: userRelations,
});
return await client.user.update({
where: {
id: user.id,
},
data: {
emojis: {
connect: emojis.map((emoji) => ({
id: emoji.id,
})),
},
instanceId: (await addInstanceIfNotExists(uriData.origin)).id,
},
include: userRelations,
});
};
/**
* Fetches the list of followers associated with the actor and updates the user's followers
*/
export const fetchFollowers = () => {
//
//
};
/**
@ -180,75 +182,75 @@ export const fetchFollowers = () => {
* @returns The newly created user.
*/
export const createNewLocalUser = async (data: {
username: string;
display_name?: string;
password: string;
email: string;
bio?: string;
avatar?: string;
header?: string;
admin?: boolean;
username: string;
display_name?: string;
password: string;
email: string;
bio?: string;
avatar?: string;
header?: string;
admin?: boolean;
}) => {
const keys = await generateUserKeys();
const keys = await generateUserKeys();
const user = await client.user.create({
data: {
username: data.username,
displayName: data.display_name ?? data.username,
password: await Bun.password.hash(data.password),
email: data.email,
note: data.bio ?? "",
avatar: data.avatar ?? config.defaults.avatar,
header: data.header ?? config.defaults.avatar,
isAdmin: data.admin ?? false,
uri: "",
publicKey: keys.public_key,
privateKey: keys.private_key,
source: {
language: null,
note: "",
privacy: "public",
sensitive: false,
fields: [],
},
},
});
const user = await client.user.create({
data: {
username: data.username,
displayName: data.display_name ?? data.username,
password: await Bun.password.hash(data.password),
email: data.email,
note: data.bio ?? "",
avatar: data.avatar ?? config.defaults.avatar,
header: data.header ?? config.defaults.avatar,
isAdmin: data.admin ?? false,
uri: "",
publicKey: keys.public_key,
privateKey: keys.private_key,
source: {
language: null,
note: "",
privacy: "public",
sensitive: false,
fields: [],
},
},
});
// Add to Meilisearch
await addUserToMeilisearch(user);
// Add to Meilisearch
await addUserToMeilisearch(user);
return await client.user.update({
where: {
id: user.id,
},
data: {
uri: `${config.http.base_url}/users/${user.id}`,
endpoints: {
disliked: `${config.http.base_url}/users/${user.id}/disliked`,
featured: `${config.http.base_url}/users/${user.id}/featured`,
liked: `${config.http.base_url}/users/${user.id}/liked`,
followers: `${config.http.base_url}/users/${user.id}/followers`,
following: `${config.http.base_url}/users/${user.id}/following`,
inbox: `${config.http.base_url}/users/${user.id}/inbox`,
outbox: `${config.http.base_url}/users/${user.id}/outbox`,
},
},
include: userRelations,
});
return await client.user.update({
where: {
id: user.id,
},
data: {
uri: `${config.http.base_url}/users/${user.id}`,
endpoints: {
disliked: `${config.http.base_url}/users/${user.id}/disliked`,
featured: `${config.http.base_url}/users/${user.id}/featured`,
liked: `${config.http.base_url}/users/${user.id}/liked`,
followers: `${config.http.base_url}/users/${user.id}/followers`,
following: `${config.http.base_url}/users/${user.id}/following`,
inbox: `${config.http.base_url}/users/${user.id}/inbox`,
outbox: `${config.http.base_url}/users/${user.id}/outbox`,
},
},
include: userRelations,
});
};
/**
* Parses mentions from a list of URIs
*/
export const parseMentionsUris = async (mentions: string[]) => {
return await client.user.findMany({
where: {
uri: {
in: mentions,
},
},
include: userRelations,
});
return await client.user.findMany({
where: {
uri: {
in: mentions,
},
},
include: userRelations,
});
};
/**
@ -257,22 +259,22 @@ export const parseMentionsUris = async (mentions: string[]) => {
* @returns The user associated with the given access token.
*/
export const retrieveUserFromToken = async (access_token: string) => {
if (!access_token) return null;
if (!access_token) return null;
const token = await client.token.findFirst({
where: {
access_token,
},
include: {
user: {
include: userRelations,
},
},
});
const token = await client.token.findFirst({
where: {
access_token,
},
include: {
user: {
include: userRelations,
},
},
});
if (!token) return null;
if (!token) return null;
return token.user;
return token.user;
};
/**
@ -281,174 +283,174 @@ export const retrieveUserFromToken = async (access_token: string) => {
* @returns The relationship to the other user.
*/
export const getRelationshipToOtherUser = async (
user: UserWithRelations,
other: User
user: UserWithRelations,
other: User,
) => {
return await client.relationship.findFirst({
where: {
ownerId: user.id,
subjectId: other.id,
},
});
return await client.relationship.findFirst({
where: {
ownerId: user.id,
subjectId: other.id,
},
});
};
/**
* Generates keys for the user.
*/
export const generateUserKeys = async () => {
const keys = await crypto.subtle.generateKey("Ed25519", true, [
"sign",
"verify",
]);
const keys = await crypto.subtle.generateKey("Ed25519", true, [
"sign",
"verify",
]);
const privateKey = btoa(
String.fromCharCode.apply(null, [
...new Uint8Array(
// jesus help me what do these letters mean
await crypto.subtle.exportKey("pkcs8", keys.privateKey)
),
])
);
const publicKey = btoa(
String.fromCharCode(
...new Uint8Array(
// why is exporting a key so hard
await crypto.subtle.exportKey("spki", keys.publicKey)
)
)
);
const privateKey = btoa(
String.fromCharCode.apply(null, [
...new Uint8Array(
// jesus help me what do these letters mean
await crypto.subtle.exportKey("pkcs8", keys.privateKey),
),
]),
);
const publicKey = btoa(
String.fromCharCode(
...new Uint8Array(
// why is exporting a key so hard
await crypto.subtle.exportKey("spki", keys.publicKey),
),
),
);
// Add header, footer and newlines later on
// These keys are base64 encrypted
return {
private_key: privateKey,
public_key: publicKey,
};
// Add header, footer and newlines later on
// These keys are base64 encrypted
return {
private_key: privateKey,
public_key: publicKey,
};
};
export const userToAPI = (
user: UserWithRelations,
isOwnAccount = false
user: UserWithRelations,
isOwnAccount = false,
): APIAccount => {
return {
id: user.id,
username: user.username,
display_name: user.displayName,
note: user.note,
url: user.uri,
avatar: getAvatarUrl(user, config),
header: getHeaderUrl(user, config),
locked: user.isLocked,
created_at: new Date(user.createdAt).toISOString(),
followers_count: user.relationshipSubjects.filter(r => r.following)
.length,
following_count: user.relationships.filter(r => r.following).length,
statuses_count: user._count.statuses,
emojis: user.emojis.map(emoji => emojiToAPI(emoji)),
// TODO: Add fields
fields: [],
bot: user.isBot,
source:
isOwnAccount && user.source
? (user.source as APISource)
: undefined,
// TODO: Add static avatar and header
avatar_static: "",
header_static: "",
acct:
user.instance === null
? user.username
: `${user.username}@${user.instance.base_url}`,
// TODO: Add these fields
limited: false,
moved: null,
noindex: false,
suspended: false,
discoverable: undefined,
mute_expires_at: undefined,
group: false,
pleroma: {
is_admin: user.isAdmin,
is_moderator: user.isAdmin,
},
};
return {
id: user.id,
username: user.username,
display_name: user.displayName,
note: user.note,
url: user.uri,
avatar: getAvatarUrl(user, config),
header: getHeaderUrl(user, config),
locked: user.isLocked,
created_at: new Date(user.createdAt).toISOString(),
followers_count: user.relationshipSubjects.filter((r) => r.following)
.length,
following_count: user.relationships.filter((r) => r.following).length,
statuses_count: user._count.statuses,
emojis: user.emojis.map((emoji) => emojiToAPI(emoji)),
// TODO: Add fields
fields: [],
bot: user.isBot,
source:
isOwnAccount && user.source
? (user.source as APISource)
: undefined,
// TODO: Add static avatar and header
avatar_static: "",
header_static: "",
acct:
user.instance === null
? user.username
: `${user.username}@${user.instance.base_url}`,
// TODO: Add these fields
limited: false,
moved: null,
noindex: false,
suspended: false,
discoverable: undefined,
mute_expires_at: undefined,
group: false,
pleroma: {
is_admin: user.isAdmin,
is_moderator: user.isAdmin,
},
};
};
/**
* Should only return local users
*/
export const userToLysand = (user: UserWithRelations): LysandUser => {
if (user.instanceId !== null) {
throw new Error("Cannot convert remote user to Lysand format");
}
if (user.instanceId !== null) {
throw new Error("Cannot convert remote user to Lysand format");
}
return {
id: user.id,
type: "User",
uri: user.uri,
bio: [
{
content: user.note,
content_type: "text/html",
},
{
content: htmlToText(user.note),
content_type: "text/plain",
},
],
created_at: new Date(user.createdAt).toISOString(),
disliked: `${user.uri}/disliked`,
featured: `${user.uri}/featured`,
liked: `${user.uri}/liked`,
followers: `${user.uri}/followers`,
following: `${user.uri}/following`,
inbox: `${user.uri}/inbox`,
outbox: `${user.uri}/outbox`,
indexable: false,
username: user.username,
avatar: [
{
content: getAvatarUrl(user, config) || "",
content_type: `image/${user.avatar.split(".")[1]}`,
},
],
header: [
{
content: getHeaderUrl(user, config) || "",
content_type: `image/${user.header.split(".")[1]}`,
},
],
display_name: user.displayName,
fields: (user.source as any as APISource).fields.map(field => ({
key: [
{
content: field.name,
content_type: "text/html",
},
{
content: htmlToText(field.name),
content_type: "text/plain",
},
],
value: [
{
content: field.value,
content_type: "text/html",
},
{
content: htmlToText(field.value),
content_type: "text/plain",
},
],
})),
public_key: {
actor: `${config.http.base_url}/users/${user.id}`,
public_key: user.publicKey,
},
extensions: {
"org.lysand:custom_emojis": {
emojis: user.emojis.map(emoji => emojiToLysand(emoji)),
},
},
};
return {
id: user.id,
type: "User",
uri: user.uri,
bio: [
{
content: user.note,
content_type: "text/html",
},
{
content: htmlToText(user.note),
content_type: "text/plain",
},
],
created_at: new Date(user.createdAt).toISOString(),
disliked: `${user.uri}/disliked`,
featured: `${user.uri}/featured`,
liked: `${user.uri}/liked`,
followers: `${user.uri}/followers`,
following: `${user.uri}/following`,
inbox: `${user.uri}/inbox`,
outbox: `${user.uri}/outbox`,
indexable: false,
username: user.username,
avatar: [
{
content: getAvatarUrl(user, config) || "",
content_type: `image/${user.avatar.split(".")[1]}`,
},
],
header: [
{
content: getHeaderUrl(user, config) || "",
content_type: `image/${user.header.split(".")[1]}`,
},
],
display_name: user.displayName,
fields: (user.source as APISource).fields.map((field) => ({
key: [
{
content: field.name,
content_type: "text/html",
},
{
content: htmlToText(field.name),
content_type: "text/plain",
},
],
value: [
{
content: field.value,
content_type: "text/html",
},
{
content: htmlToText(field.value),
content_type: "text/plain",
},
],
})),
public_key: {
actor: `${config.http.base_url}/users/${user.id}`,
public_key: user.publicKey,
},
extensions: {
"org.lysand:custom_emojis": {
emojis: user.emojis.map((emoji) => emojiToLysand(emoji)),
},
},
};
};

View file

@ -1,111 +1,111 @@
import type { Prisma } from "@prisma/client";
export const userRelations: Prisma.UserInclude = {
emojis: true,
instance: true,
likes: true,
relationships: true,
relationshipSubjects: true,
pinnedNotes: true,
_count: {
select: {
statuses: true,
likes: true,
},
},
emojis: true,
instance: true,
likes: true,
relationships: true,
relationshipSubjects: true,
pinnedNotes: true,
_count: {
select: {
statuses: true,
likes: true,
},
},
};
export const statusAndUserRelations: Prisma.StatusInclude = {
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: true,
},
},
instance: true,
mentions: true,
pinnedBy: true,
_count: {
select: {
replies: true,
},
},
},
},
reblogs: true,
attachments: true,
instance: true,
mentions: {
include: userRelations,
},
pinnedBy: true,
_count: {
select: {
replies: true,
likes: true,
reblogs: true,
},
},
reblog: {
include: {
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: true,
},
},
instance: true,
mentions: {
include: userRelations,
},
pinnedBy: true,
_count: {
select: {
replies: true,
},
},
},
},
quotingPost: {
include: {
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: true,
},
},
instance: true,
mentions: true,
pinnedBy: true,
_count: {
select: {
replies: true,
},
},
},
},
likes: {
include: {
liker: true,
},
},
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: true,
},
},
instance: true,
mentions: true,
pinnedBy: true,
_count: {
select: {
replies: true,
},
},
},
},
reblogs: true,
attachments: true,
instance: true,
mentions: {
include: userRelations,
},
pinnedBy: true,
_count: {
select: {
replies: true,
likes: true,
reblogs: true,
},
},
reblog: {
include: {
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: true,
},
},
instance: true,
mentions: {
include: userRelations,
},
pinnedBy: true,
_count: {
select: {
replies: true,
},
},
},
},
quotingPost: {
include: {
author: {
include: userRelations,
},
application: true,
emojis: true,
inReplyToPost: {
include: {
author: true,
},
},
instance: true,
mentions: true,
pinnedBy: true,
_count: {
select: {
replies: true,
},
},
},
},
likes: {
include: {
liker: true,
},
},
};

View file

@ -1,73 +1,75 @@
import { exists, mkdir } from "node:fs/promises";
import { connectMeili } from "@meilisearch";
import { moduleIsEntry } from "@module";
import type { PrismaClientInitializationError } from "@prisma/client/runtime/library";
import { initializeRedisCache } from "@redis";
import { connectMeili } from "@meilisearch";
import { config } from "config-manager";
import { client } from "~database/datasource";
import { LogLevel, LogManager, MultiLogManager } from "log-manager";
import { moduleIsEntry } from "@module";
import { client } from "~database/datasource";
import { createServer } from "~server";
import { exists, mkdir } from "fs/promises";
const timeAtStart = performance.now();
const requests_log = Bun.file(process.cwd() + "/logs/requests.log");
const requests_log = Bun.file(`${process.cwd()}/logs/requests.log`);
const isEntry = moduleIsEntry(import.meta.url);
// If imported as a module, redirect logs to /dev/null to not pollute console (e.g. in tests)
const logger = new LogManager(isEntry ? requests_log : Bun.file(`/dev/null`));
const logger = new LogManager(isEntry ? requests_log : Bun.file("/dev/null"));
const consoleLogger = new LogManager(
isEntry ? Bun.stdout : Bun.file(`/dev/null`)
isEntry ? Bun.stdout : Bun.file("/dev/null"),
);
const dualLogger = new MultiLogManager([logger, consoleLogger]);
if (!(await exists(config.logging.storage.requests))) {
await consoleLogger.log(
LogLevel.WARNING,
"Lysand",
`Creating logs directory at ${process.cwd()}/logs/`
);
await consoleLogger.log(
LogLevel.WARNING,
"Lysand",
`Creating logs directory at ${process.cwd()}/logs/`,
);
await mkdir(process.cwd() + "/logs/");
await mkdir(`${process.cwd()}/logs/`);
}
await dualLogger.log(LogLevel.INFO, "Lysand", "Starting Lysand...");
// NODE_ENV seems to be broken and output `development` even when set to production, so use the flag instead
const isProd =
process.env.NODE_ENV === "production" || process.argv.includes("--prod");
process.env.NODE_ENV === "production" || process.argv.includes("--prod");
const redisCache = await initializeRedisCache();
if (config.meilisearch.enabled) {
await connectMeili(dualLogger);
await connectMeili(dualLogger);
}
if (redisCache) {
client.$use(redisCache);
client.$use(redisCache);
}
// Check if database is reachable
let postCount = 0;
try {
postCount = await client.status.count();
postCount = await client.status.count();
} catch (e) {
const error = e as PrismaClientInitializationError;
await logger.logError(LogLevel.CRITICAL, "Database", error);
await consoleLogger.logError(LogLevel.CRITICAL, "Database", error);
process.exit(1);
const error = e as PrismaClientInitializationError;
await logger.logError(LogLevel.CRITICAL, "Database", error);
await consoleLogger.logError(LogLevel.CRITICAL, "Database", error);
process.exit(1);
}
const server = createServer(config, dualLogger, isProd);
await dualLogger.log(
LogLevel.INFO,
"Server",
`Lysand started at ${config.http.bind}:${config.http.bind_port} in ${(performance.now() - timeAtStart).toFixed(0)}ms`
LogLevel.INFO,
"Server",
`Lysand started at ${config.http.bind}:${config.http.bind_port} in ${(
performance.now() - timeAtStart
).toFixed(0)}ms`,
);
await dualLogger.log(
LogLevel.INFO,
"Database",
`Database is online, now serving ${postCount} posts`
LogLevel.INFO,
"Database",
`Database is online, now serving ${postCount} posts`,
);
export { config, server };

View file

@ -1,130 +1,118 @@
{
"name": "lysand",
"module": "index.ts",
"type": "module",
"version": "0.3.0",
"description": "A project to build a federated social network",
"author": {
"email": "contact@cpluspatch.com",
"name": "CPlusPatch",
"url": "https://cpluspatch.com"
},
"bugs": {
"url": "https://github.com/lysand-org/lysand/issues"
},
"icon": "https://github.com/lysand-org/lysand",
"license": "AGPL-3.0",
"keywords": [
"federated",
"activitypub",
"bun"
],
"workspaces": ["packages/*"],
"maintainers": [
{
"email": "contact@cpluspatch.com",
"name": "CPlusPatch",
"url": "https://cpluspatch.com"
"name": "lysand",
"module": "index.ts",
"type": "module",
"version": "0.3.0",
"description": "A project to build a federated social network",
"author": {
"email": "contact@cpluspatch.com",
"name": "CPlusPatch",
"url": "https://cpluspatch.com"
},
"bugs": {
"url": "https://github.com/lysand-org/lysand/issues"
},
"icon": "https://github.com/lysand-org/lysand",
"license": "AGPL-3.0",
"keywords": ["federated", "activitypub", "bun"],
"workspaces": ["packages/*"],
"maintainers": [
{
"email": "contact@cpluspatch.com",
"name": "CPlusPatch",
"url": "https://cpluspatch.com"
}
],
"repository": {
"type": "git",
"url": "git+https://github.com/lysand-org/lysand.git"
},
"private": true,
"scripts": {
"dev": "bun run --watch index.ts",
"vite:dev": "bunx --bun vite pages",
"vite:build": "bunx --bun vite build pages",
"start": "NODE_ENV=production bun run dist/index.js --prod",
"migrate-dev": "bun prisma migrate dev",
"migrate": "bun prisma migrate deploy",
"lint": "bunx --bun eslint --config .eslintrc.cjs --ext .ts .",
"prod-build": "bunx --bun vite build pages && bun run build.ts",
"prisma": "DATABASE_URL=$(bun run prisma.ts) bunx prisma",
"generate": "bun prisma generate",
"benchmark:timeline": "bun run benchmarks/timelines.ts",
"cloc": "cloc . --exclude-dir node_modules,dist",
"cli": "bun run cli.ts"
},
"trustedDependencies": [
"@biomejs/biome",
"@prisma/client",
"@prisma/engines",
"esbuild",
"prisma",
"sharp"
],
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@julr/unocss-preset-forms": "^0.1.0",
"@types/cli-table": "^0.3.4",
"@types/html-to-text": "^9.0.4",
"@types/ioredis": "^5.0.0",
"@types/jsonld": "^1.5.13",
"@typescript-eslint/eslint-plugin": "latest",
"@unocss/cli": "latest",
"@vitejs/plugin-vue": "latest",
"@vueuse/head": "^2.0.0",
"activitypub-types": "^1.0.3",
"bun-types": "latest",
"typescript": "latest",
"unocss": "latest",
"untyped": "^1.4.2",
"vite": "latest",
"vite-ssr": "^0.17.1",
"vue": "^3.3.9",
"vue-router": "^4.2.5",
"vue-tsc": "latest"
},
"peerDependencies": {
"typescript": "^5.3.2"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.461.0",
"@iarna/toml": "^2.2.5",
"@json2csv/plainjs": "^7.0.6",
"@prisma/client": "^5.6.0",
"blurhash": "^2.0.5",
"bullmq": "latest",
"c12": "^1.10.0",
"chalk": "^5.3.0",
"cli-parser": "workspace:*",
"cli-table": "^0.3.11",
"config-manager": "workspace:*",
"eventemitter3": "^5.0.1",
"extract-zip": "^2.0.1",
"html-to-text": "^9.0.5",
"ioredis": "^5.3.2",
"ip-matching": "^2.1.2",
"iso-639-1": "^3.1.0",
"isomorphic-dompurify": "latest",
"jsonld": "^8.3.1",
"linkify-html": "^4.1.3",
"linkify-string": "^4.1.3",
"linkifyjs": "^4.1.3",
"log-manager": "workspace:*",
"marked": "latest",
"media-manager": "workspace:*",
"megalodon": "^10.0.0",
"meilisearch": "latest",
"merge-deep-ts": "^1.2.6",
"next-route-matcher": "^1.0.1",
"oauth4webapi": "^2.4.0",
"prisma": "^5.6.0",
"prisma-json-types-generator": "^3.0.4",
"prisma-redis-middleware": "^4.8.0",
"request-parser": "workspace:*",
"semver": "^7.5.4",
"sharp": "^0.33.0-rc.2",
"strip-ansi": "^7.1.0"
}
],
"repository": {
"type": "git",
"url": "git+https://github.com/lysand-org/lysand.git"
},
"private": true,
"scripts": {
"dev": "bun run --watch index.ts",
"vite:dev": "bunx --bun vite pages",
"vite:build": "bunx --bun vite build pages",
"start": "NODE_ENV=production bun run dist/index.js --prod",
"migrate-dev": "bun prisma migrate dev",
"migrate": "bun prisma migrate deploy",
"lint": "bunx --bun eslint --config .eslintrc.cjs --ext .ts .",
"prod-build": "bunx --bun vite build pages && bun run build.ts",
"prisma": "DATABASE_URL=$(bun run prisma.ts) bunx prisma",
"generate": "bun prisma generate",
"benchmark:timeline": "bun run benchmarks/timelines.ts",
"cloc": "cloc . --exclude-dir node_modules,dist",
"cli": "bun run cli.ts"
},
"trustedDependencies": [
"@biomejs/biome",
"@prisma/client",
"@prisma/engines",
"esbuild",
"prisma",
"sharp"
],
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@julr/unocss-preset-forms": "^0.1.0",
"@microsoft/eslint-formatter-sarif": "^3.0.0",
"@types/cli-table": "^0.3.4",
"@types/html-to-text": "^9.0.4",
"@types/ioredis": "^5.0.0",
"@types/jsonld": "^1.5.13",
"@typescript-eslint/eslint-plugin": "latest",
"@typescript-eslint/parser": "latest",
"@unocss/cli": "latest",
"@vitejs/plugin-vue": "latest",
"@vueuse/head": "^2.0.0",
"activitypub-types": "^1.0.3",
"bun-types": "latest",
"eslint": "^8.54.0",
"eslint-config-prettier": "^9.0.0",
"eslint-formatter-pretty": "^6.0.0",
"eslint-formatter-summary": "^1.1.0",
"eslint-plugin-prettier": "^5.0.1",
"prettier": "^3.1.0",
"typescript": "latest",
"unocss": "latest",
"untyped": "^1.4.2",
"vite": "latest",
"vite-ssr": "^0.17.1",
"vue": "^3.3.9",
"vue-router": "^4.2.5",
"vue-tsc": "latest"
},
"peerDependencies": {
"typescript": "^5.3.2"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.461.0",
"@iarna/toml": "^2.2.5",
"@json2csv/plainjs": "^7.0.6",
"@prisma/client": "^5.6.0",
"blurhash": "^2.0.5",
"bullmq": "latest",
"c12": "^1.10.0",
"chalk": "^5.3.0",
"cli-parser": "workspace:*",
"cli-table": "^0.3.11",
"config-manager": "workspace:*",
"eventemitter3": "^5.0.1",
"extract-zip": "^2.0.1",
"html-to-text": "^9.0.5",
"ioredis": "^5.3.2",
"ip-matching": "^2.1.2",
"iso-639-1": "^3.1.0",
"isomorphic-dompurify": "latest",
"jsonld": "^8.3.1",
"linkify-html": "^4.1.3",
"linkify-string": "^4.1.3",
"linkifyjs": "^4.1.3",
"log-manager": "workspace:*",
"marked": "latest",
"media-manager": "workspace:*",
"megalodon": "^10.0.0",
"meilisearch": "latest",
"merge-deep-ts": "^1.2.6",
"next-route-matcher": "^1.0.1",
"oauth4webapi": "^2.4.0",
"prisma": "^5.6.0",
"prisma-json-types-generator": "^3.0.4",
"prisma-redis-middleware": "^4.8.0",
"request-parser": "workspace:*",
"semver": "^7.5.4",
"sharp": "^0.33.0-rc.2",
"strip-ansi": "^7.1.0"
}
}

View file

@ -1,23 +1,23 @@
export interface CliParameter {
name: string;
/* Like -v for --version */
shortName?: string;
/**
* If not positioned, the argument will need to be called with --name value instead of just value
* @default true
*/
positioned?: boolean;
/* Whether the argument needs a value (requires positioned to be false) */
needsValue?: boolean;
optional?: true;
type: CliParameterType;
description?: string;
name: string;
/* Like -v for --version */
shortName?: string;
/**
* If not positioned, the argument will need to be called with --name value instead of just value
* @default true
*/
positioned?: boolean;
/* Whether the argument needs a value (requires positioned to be false) */
needsValue?: boolean;
optional?: true;
type: CliParameterType;
description?: string;
}
export enum CliParameterType {
STRING = "string",
NUMBER = "number",
BOOLEAN = "boolean",
ARRAY = "array",
EMPTY = "empty",
STRING = "string",
NUMBER = "number",
BOOLEAN = "boolean",
ARRAY = "array",
EMPTY = "empty",
}

View file

@ -1,18 +1,18 @@
import { CliParameterType, type CliParameter } from "./cli-builder.type";
import chalk from "chalk";
import strip from "strip-ansi";
import { type CliParameter, CliParameterType } from "./cli-builder.type";
export function startsWithArray(fullArray: any[], startArray: any[]) {
if (startArray.length > fullArray.length) {
return false;
}
return fullArray
.slice(0, startArray.length)
.every((value, index) => value === startArray[index]);
export function startsWithArray(fullArray: string[], startArray: string[]) {
if (startArray.length > fullArray.length) {
return false;
}
return fullArray
.slice(0, startArray.length)
.every((value, index) => value === startArray[index]);
}
interface TreeType {
[key: string]: CliCommand | TreeType;
[key: string]: CliCommand | TreeType;
}
/**
@ -20,178 +20,186 @@ interface TreeType {
* @param commands Array of commands to register
*/
export class CliBuilder {
constructor(public commands: CliCommand[] = []) {}
constructor(public commands: CliCommand[] = []) {}
/**
* Add command to the CLI
* @throws Error if command already exists
* @param command Command to add
*/
registerCommand(command: CliCommand) {
if (this.checkIfCommandAlreadyExists(command)) {
throw new Error(
`Command category '${command.categories.join(" ")}' already exists`
);
}
this.commands.push(command);
}
/**
* Add command to the CLI
* @throws Error if command already exists
* @param command Command to add
*/
registerCommand(command: CliCommand) {
if (this.checkIfCommandAlreadyExists(command)) {
throw new Error(
`Command category '${command.categories.join(
" ",
)}' already exists`,
);
}
this.commands.push(command);
}
/**
* Add multiple commands to the CLI
* @throws Error if command already exists
* @param commands Commands to add
*/
registerCommands(commands: CliCommand[]) {
const existingCommand = commands.find(command =>
this.checkIfCommandAlreadyExists(command)
);
if (existingCommand) {
throw new Error(
`Command category '${existingCommand.categories.join(" ")}' already exists`
);
}
this.commands.push(...commands);
}
/**
* Add multiple commands to the CLI
* @throws Error if command already exists
* @param commands Commands to add
*/
registerCommands(commands: CliCommand[]) {
const existingCommand = commands.find((command) =>
this.checkIfCommandAlreadyExists(command),
);
if (existingCommand) {
throw new Error(
`Command category '${existingCommand.categories.join(
" ",
)}' already exists`,
);
}
this.commands.push(...commands);
}
/**
* Remove command from the CLI
* @param command Command to remove
*/
deregisterCommand(command: CliCommand) {
this.commands = this.commands.filter(
registeredCommand => registeredCommand !== command
);
}
/**
* Remove command from the CLI
* @param command Command to remove
*/
deregisterCommand(command: CliCommand) {
this.commands = this.commands.filter(
(registeredCommand) => registeredCommand !== command,
);
}
/**
* Remove multiple commands from the CLI
* @param commands Commands to remove
*/
deregisterCommands(commands: CliCommand[]) {
this.commands = this.commands.filter(
registeredCommand => !commands.includes(registeredCommand)
);
}
/**
* Remove multiple commands from the CLI
* @param commands Commands to remove
*/
deregisterCommands(commands: CliCommand[]) {
this.commands = this.commands.filter(
(registeredCommand) => !commands.includes(registeredCommand),
);
}
checkIfCommandAlreadyExists(command: CliCommand) {
return this.commands.some(
registeredCommand =>
registeredCommand.categories.length ==
command.categories.length &&
registeredCommand.categories.every(
(category, index) => category === command.categories[index]
)
);
}
checkIfCommandAlreadyExists(command: CliCommand) {
return this.commands.some(
(registeredCommand) =>
registeredCommand.categories.length ===
command.categories.length &&
registeredCommand.categories.every(
(category, index) => category === command.categories[index],
),
);
}
/**
* Get relevant args for the command (without executable or runtime)
* @param args Arguments passed to the CLI
*/
private getRelevantArgs(args: string[]) {
if (args[0].startsWith("./")) {
// Formatted like ./cli.ts [command]
return args.slice(1);
} else if (args[0].includes("bun")) {
// Formatted like bun cli.ts [command]
return args.slice(2);
} else {
return args;
}
}
/**
* Get relevant args for the command (without executable or runtime)
* @param args Arguments passed to the CLI
*/
private getRelevantArgs(args: string[]) {
if (args[0].startsWith("./")) {
// Formatted like ./cli.ts [command]
return args.slice(1);
}
if (args[0].includes("bun")) {
// Formatted like bun cli.ts [command]
return args.slice(2);
}
return args;
}
/**
* Turn raw system args into a CLI command and run it
* @param args Args directly from process.argv
*/
async processArgs(args: string[]) {
const revelantArgs = this.getRelevantArgs(args);
/**
* Turn raw system args into a CLI command and run it
* @param args Args directly from process.argv
*/
async processArgs(args: string[]) {
const revelantArgs = this.getRelevantArgs(args);
// Handle "-h", "--help" and "help" commands as special cases
if (revelantArgs.length === 1) {
if (["-h", "--help", "help"].includes(revelantArgs[0])) {
this.displayHelp();
return;
}
}
// Handle "-h", "--help" and "help" commands as special cases
if (revelantArgs.length === 1) {
if (["-h", "--help", "help"].includes(revelantArgs[0])) {
this.displayHelp();
return;
}
}
// Find revelant command
// Search for a command with as many categories matching args as possible
const matchingCommands = this.commands.filter(command =>
startsWithArray(revelantArgs, command.categories)
);
// Find revelant command
// Search for a command with as many categories matching args as possible
const matchingCommands = this.commands.filter((command) =>
startsWithArray(revelantArgs, command.categories),
);
if (matchingCommands.length === 0) {
console.log(
`Invalid command "${revelantArgs.join(" ")}". Please use the ${chalk.bold("help")} command to see a list of commands`
);
return 0;
}
if (matchingCommands.length === 0) {
console.log(
`Invalid command "${revelantArgs.join(
" ",
)}". Please use the ${chalk.bold(
"help",
)} command to see a list of commands`,
);
return 0;
}
// Get command with largest category size
const command = matchingCommands.reduce((prev, current) =>
prev.categories.length > current.categories.length ? prev : current
);
// Get command with largest category size
const command = matchingCommands.reduce((prev, current) =>
prev.categories.length > current.categories.length ? prev : current,
);
const argsWithoutCategories = revelantArgs.slice(
command.categories.length
);
const argsWithoutCategories = revelantArgs.slice(
command.categories.length,
);
return await command.run(argsWithoutCategories);
}
return await command.run(argsWithoutCategories);
}
/**
* Recursively urns the commands into a tree where subcategories mark each sub-branch
* @example
* ```txt
* user verify
* user delete
* user new admin
* user new
* ->
* user
* verify
* delete
* new
* admin
* ""
* ```
*/
getCommandTree(commands: CliCommand[]): TreeType {
const tree: TreeType = {};
/**
* Recursively urns the commands into a tree where subcategories mark each sub-branch
* @example
* ```txt
* user verify
* user delete
* user new admin
* user new
* ->
* user
* verify
* delete
* new
* admin
* ""
* ```
*/
getCommandTree(commands: CliCommand[]): TreeType {
const tree: TreeType = {};
for (const command of commands) {
let currentLevel = tree; // Start at the root
for (const command of commands) {
let currentLevel = tree; // Start at the root
// Split the command into parts and iterate over them
for (const part of command.categories) {
// If this part doesn't exist in the current level of the tree, add it (__proto__ check to prevent prototype pollution)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!currentLevel[part] && part !== "__proto__") {
// If this is the last part of the command, add the command itself
if (
part ===
command.categories[command.categories.length - 1]
) {
currentLevel[part] = command;
break;
}
currentLevel[part] = {};
}
// Split the command into parts and iterate over them
for (const part of command.categories) {
// If this part doesn't exist in the current level of the tree, add it (__proto__ check to prevent prototype pollution)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!currentLevel[part] && part !== "__proto__") {
// If this is the last part of the command, add the command itself
if (
part ===
command.categories[command.categories.length - 1]
) {
currentLevel[part] = command;
break;
}
currentLevel[part] = {};
}
// Move down to the next level of the tree
currentLevel = currentLevel[part] as TreeType;
}
}
// Move down to the next level of the tree
currentLevel = currentLevel[part] as TreeType;
}
}
return tree;
}
return tree;
}
/**
* Display help for every command in a tree manner
*/
displayHelp() {
/*
/**
* Display help for every command in a tree manner
*/
displayHelp() {
/*
user
set
admin: List of admin commands
@ -204,217 +212,242 @@ export class CliBuilder {
verify
...
*/
const tree = this.getCommandTree(this.commands);
let writeBuffer = "";
const tree = this.getCommandTree(this.commands);
let writeBuffer = "";
const displayTree = (tree: TreeType, depth = 0) => {
for (const [key, value] of Object.entries(tree)) {
if (value instanceof CliCommand) {
writeBuffer += `${" ".repeat(depth)}${chalk.blue(key)}|${chalk.underline(value.description)}\n`;
const positionedArgs = value.argTypes.filter(
arg => arg.positioned ?? true
);
const unpositionedArgs = value.argTypes.filter(
arg => !(arg.positioned ?? true)
);
const displayTree = (tree: TreeType, depth = 0) => {
for (const [key, value] of Object.entries(tree)) {
if (value instanceof CliCommand) {
writeBuffer += `${" ".repeat(depth)}${chalk.blue(
key,
)}|${chalk.underline(value.description)}\n`;
const positionedArgs = value.argTypes.filter(
(arg) => arg.positioned ?? true,
);
const unpositionedArgs = value.argTypes.filter(
(arg) => !(arg.positioned ?? true),
);
for (const arg of positionedArgs) {
writeBuffer += `${" ".repeat(depth + 1)}${chalk.green(
arg.name
)}|${
arg.description ?? "(no description)"
} ${arg.optional ? chalk.gray("(optional)") : ""}\n`;
}
for (const arg of unpositionedArgs) {
writeBuffer += `${" ".repeat(depth + 1)}${chalk.yellow("--" + arg.name)}${arg.shortName ? ", " + chalk.yellow("-" + arg.shortName) : ""}|${
arg.description ?? "(no description)"
} ${arg.optional ? chalk.gray("(optional)") : ""}\n`;
}
for (const arg of positionedArgs) {
writeBuffer += `${" ".repeat(
depth + 1,
)}${chalk.green(arg.name)}|${
arg.description ?? "(no description)"
} ${arg.optional ? chalk.gray("(optional)") : ""}\n`;
}
for (const arg of unpositionedArgs) {
writeBuffer += `${" ".repeat(
depth + 1,
)}${chalk.yellow(`--${arg.name}`)}${
arg.shortName
? `, ${chalk.yellow(`-${arg.shortName}`)}`
: ""
}|${arg.description ?? "(no description)"} ${
arg.optional ? chalk.gray("(optional)") : ""
}\n`;
}
if (value.example) {
writeBuffer += `${" ".repeat(depth + 1)}${chalk.bold("Example:")} ${chalk.bgGray(
value.example
)}\n`;
}
} else {
writeBuffer += `${" ".repeat(depth)}${chalk.blue(key)}\n`;
displayTree(value, depth + 1);
}
}
};
if (value.example) {
writeBuffer += `${" ".repeat(depth + 1)}${chalk.bold(
"Example:",
)} ${chalk.bgGray(value.example)}\n`;
}
} else {
writeBuffer += `${" ".repeat(depth)}${chalk.blue(
key,
)}\n`;
displayTree(value, depth + 1);
}
}
};
displayTree(tree);
displayTree(tree);
// Replace all "|" with enough dots so that the text on the left + the dots = the same length
const optimal_length = Number(
// @ts-expect-error Slightly hacky but works
writeBuffer.split("\n").reduce((prev, current) => {
// If previousValue is empty
if (!prev)
return current.includes("|")
? current.split("|")[0].length
: 0;
if (!current.includes("|")) return prev;
const [left] = current.split("|");
// Strip ANSI color codes or they mess up the length
return Math.max(Number(prev), strip(left).length);
})
);
// Replace all "|" with enough dots so that the text on the left + the dots = the same length
const optimal_length = Number(
writeBuffer
.split("\n")
// @ts-expect-error I don't know how this works and I don't want to know
.reduce((prev, current) => {
// If previousValue is empty
if (!prev)
return current.includes("|")
? current.split("|")[0].length
: 0;
if (!current.includes("|")) return prev;
const [left] = current.split("|");
// Strip ANSI color codes or they mess up the length
return Math.max(Number(prev), Bun.stringWidth(left));
}),
);
for (const line of writeBuffer.split("\n")) {
const [left, right] = line.split("|");
if (!right) {
console.log(left);
continue;
}
// Strip ANSI color codes or they mess up the length
const dots = ".".repeat(optimal_length + 5 - strip(left).length);
console.log(`${left}${dots}${right}`);
}
}
for (const line of writeBuffer.split("\n")) {
const [left, right] = line.split("|");
if (!right) {
console.log(left);
continue;
}
// Strip ANSI color codes or they mess up the length
const dots = ".".repeat(optimal_length + 5 - Bun.stringWidth(left));
console.log(`${left}${dots}${right}`);
}
}
}
type ExecuteFunction<T> = (
instance: CliCommand,
args: Partial<T>
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
instance: CliCommand,
args: Partial<T>,
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
) => Promise<number> | Promise<void> | number | void;
/**
* A command that can be executed from the command line
* @param categories Example: `["user", "create"]` for the command `./cli user create --name John`
*/
export class CliCommand<T = any> {
constructor(
public categories: string[],
public argTypes: CliParameter[],
private execute: ExecuteFunction<T>,
public description?: string,
public example?: string
) {}
/**
* Display help message for the command
* formatted with Chalk and with emojis
*/
displayHelp() {
const positionedArgs = this.argTypes.filter(
arg => arg.positioned ?? true
);
const unpositionedArgs = this.argTypes.filter(
arg => !(arg.positioned ?? true)
);
const helpMessage = `
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export class CliCommand<T = any> {
constructor(
public categories: string[],
public argTypes: CliParameter[],
private execute: ExecuteFunction<T>,
public description?: string,
public example?: string,
) {}
/**
* Display help message for the command
* formatted with Chalk and with emojis
*/
displayHelp() {
const positionedArgs = this.argTypes.filter(
(arg) => arg.positioned ?? true,
);
const unpositionedArgs = this.argTypes.filter(
(arg) => !(arg.positioned ?? true),
);
const helpMessage = `
${chalk.green("📚 Command:")} ${chalk.yellow(this.categories.join(" "))}
${this.description ? `${chalk.cyan(this.description)}\n` : ""}
${chalk.magenta("🔧 Arguments:")}
${positionedArgs
.map(
arg =>
`${chalk.bold(arg.name)}: ${chalk.blue(arg.description ?? "(no description)")} ${
arg.optional ? chalk.gray("(optional)") : ""
}`
)
.join("\n")}
.map(
(arg) =>
`${chalk.bold(arg.name)}: ${chalk.blue(
arg.description ?? "(no description)",
)} ${arg.optional ? chalk.gray("(optional)") : ""}`,
)
.join("\n")}
${unpositionedArgs
.map(
arg =>
`--${chalk.bold(arg.name)}${arg.shortName ? `, -${arg.shortName}` : ""}: ${chalk.blue(arg.description ?? "(no description)")} ${
arg.optional ? chalk.gray("(optional)") : ""
}`
)
.join(
"\n"
)}${this.example ? `\n${chalk.magenta("🚀 Example:")}\n${chalk.bgGray(this.example)}` : ""}
.map(
(arg) =>
`--${chalk.bold(arg.name)}${
arg.shortName ? `, -${arg.shortName}` : ""
}: ${chalk.blue(arg.description ?? "(no description)")} ${
arg.optional ? chalk.gray("(optional)") : ""
}`,
)
.join("\n")}${
this.example
? `\n${chalk.magenta("🚀 Example:")}\n${chalk.bgGray(this.example)}`
: ""
}
`;
console.log(helpMessage);
}
console.log(helpMessage);
}
/**
* Parses string array arguments into a full JavaScript object
* @param argsWithoutCategories
* @returns
*/
private parseArgs(argsWithoutCategories: string[]): Record<string, any> {
const parsedArgs: Record<string, any> = {};
let currentParameter: CliParameter | null = null;
/**
* Parses string array arguments into a full JavaScript object
* @param argsWithoutCategories
* @returns
*/
private parseArgs(
argsWithoutCategories: string[],
): Record<string, string | number | boolean | string[]> {
const parsedArgs: Record<string, string | number | boolean | string[]> =
{};
let currentParameter: CliParameter | null = null;
for (let i = 0; i < argsWithoutCategories.length; i++) {
const arg = argsWithoutCategories[i];
for (let i = 0; i < argsWithoutCategories.length; i++) {
const arg = argsWithoutCategories[i];
if (arg.startsWith("--")) {
const argName = arg.substring(2);
currentParameter =
this.argTypes.find(argType => argType.name === argName) ||
null;
if (currentParameter && !currentParameter.needsValue) {
parsedArgs[argName] = true;
currentParameter = null;
} else if (currentParameter && currentParameter.needsValue) {
parsedArgs[argName] = this.castArgValue(
argsWithoutCategories[i + 1],
currentParameter.type
);
i++;
currentParameter = null;
}
} else if (arg.startsWith("-")) {
const shortName = arg.substring(1);
const argType = this.argTypes.find(
argType => argType.shortName === shortName
);
if (argType && !argType.needsValue) {
parsedArgs[argType.name] = true;
} else if (argType && argType.needsValue) {
parsedArgs[argType.name] = this.castArgValue(
argsWithoutCategories[i + 1],
argType.type
);
i++;
}
} else if (currentParameter) {
parsedArgs[currentParameter.name] = this.castArgValue(
arg,
currentParameter.type
);
currentParameter = null;
} else {
const positionedArgType = this.argTypes.find(
argType => argType.positioned && !parsedArgs[argType.name]
);
if (positionedArgType) {
parsedArgs[positionedArgType.name] = this.castArgValue(
arg,
positionedArgType.type
);
}
}
}
if (arg.startsWith("--")) {
const argName = arg.substring(2);
currentParameter =
this.argTypes.find((argType) => argType.name === argName) ||
null;
if (currentParameter && !currentParameter.needsValue) {
parsedArgs[argName] = true;
currentParameter = null;
} else if (currentParameter?.needsValue) {
parsedArgs[argName] = this.castArgValue(
argsWithoutCategories[i + 1],
currentParameter.type,
);
i++;
currentParameter = null;
}
} else if (arg.startsWith("-")) {
const shortName = arg.substring(1);
const argType = this.argTypes.find(
(argType) => argType.shortName === shortName,
);
if (argType && !argType.needsValue) {
parsedArgs[argType.name] = true;
} else if (argType?.needsValue) {
parsedArgs[argType.name] = this.castArgValue(
argsWithoutCategories[i + 1],
argType.type,
);
i++;
}
} else if (currentParameter) {
parsedArgs[currentParameter.name] = this.castArgValue(
arg,
currentParameter.type,
);
currentParameter = null;
} else {
const positionedArgType = this.argTypes.find(
(argType) =>
argType.positioned && !parsedArgs[argType.name],
);
if (positionedArgType) {
parsedArgs[positionedArgType.name] = this.castArgValue(
arg,
positionedArgType.type,
);
}
}
}
return parsedArgs;
}
return parsedArgs;
}
private castArgValue(value: string, type: CliParameter["type"]): any {
switch (type) {
case CliParameterType.STRING:
return value;
case CliParameterType.NUMBER:
return Number(value);
case CliParameterType.BOOLEAN:
return value === "true";
case CliParameterType.ARRAY:
return value.split(",");
default:
return value;
}
}
private castArgValue(
value: string,
type: CliParameter["type"],
): string | number | boolean | string[] {
switch (type) {
case CliParameterType.STRING:
return value;
case CliParameterType.NUMBER:
return Number(value);
case CliParameterType.BOOLEAN:
return value === "true";
case CliParameterType.ARRAY:
return value.split(",");
default:
return value;
}
}
/**
* Runs the execute function with the parsed parameters as an argument
*/
async run(argsWithoutCategories: string[]) {
const args = this.parseArgs(argsWithoutCategories);
return await this.execute(this, args as any);
}
/**
* Runs the execute function with the parsed parameters as an argument
*/
async run(argsWithoutCategories: string[]) {
const args = this.parseArgs(argsWithoutCategories);
return await this.execute(this, args as T);
}
}

View file

@ -1,6 +1,6 @@
{
"name": "cli-parser",
"version": "0.0.0",
"main": "index.ts",
"dependencies": { "chalk": "^5.3.0", "strip-ansi": "^7.1.0" }
"name": "cli-parser",
"version": "0.0.0",
"main": "index.ts",
"dependencies": { "chalk": "^5.3.0", "strip-ansi": "^7.1.0" }
}

View file

@ -1,485 +1,488 @@
// FILEPATH: /home/jessew/Dev/lysand/packages/cli-parser/index.test.ts
import { CliCommand, CliBuilder, startsWithArray } from "..";
import { describe, beforeEach, it, expect, jest, spyOn } from "bun:test";
import { beforeEach, describe, expect, it, jest, spyOn } from "bun:test";
import stripAnsi from "strip-ansi";
// FILEPATH: /home/jessew/Dev/lysand/packages/cli-parser/index.test.ts
import { CliBuilder, CliCommand, startsWithArray } from "..";
import { CliParameterType } from "../cli-builder.type";
describe("startsWithArray", () => {
it("should return true when fullArray starts with startArray", () => {
const fullArray = ["a", "b", "c", "d", "e"];
const startArray = ["a", "b", "c"];
expect(startsWithArray(fullArray, startArray)).toBe(true);
});
it("should return true when fullArray starts with startArray", () => {
const fullArray = ["a", "b", "c", "d", "e"];
const startArray = ["a", "b", "c"];
expect(startsWithArray(fullArray, startArray)).toBe(true);
});
it("should return false when fullArray does not start with startArray", () => {
const fullArray = ["a", "b", "c", "d", "e"];
const startArray = ["b", "c", "d"];
expect(startsWithArray(fullArray, startArray)).toBe(false);
});
it("should return false when fullArray does not start with startArray", () => {
const fullArray = ["a", "b", "c", "d", "e"];
const startArray = ["b", "c", "d"];
expect(startsWithArray(fullArray, startArray)).toBe(false);
});
it("should return true when startArray is empty", () => {
const fullArray = ["a", "b", "c", "d", "e"];
const startArray: any[] = [];
expect(startsWithArray(fullArray, startArray)).toBe(true);
});
it("should return true when startArray is empty", () => {
const fullArray = ["a", "b", "c", "d", "e"];
const startArray: string[] = [];
expect(startsWithArray(fullArray, startArray)).toBe(true);
});
it("should return false when fullArray is shorter than startArray", () => {
const fullArray = ["a", "b", "c"];
const startArray = ["a", "b", "c", "d", "e"];
expect(startsWithArray(fullArray, startArray)).toBe(false);
});
it("should return false when fullArray is shorter than startArray", () => {
const fullArray = ["a", "b", "c"];
const startArray = ["a", "b", "c", "d", "e"];
expect(startsWithArray(fullArray, startArray)).toBe(false);
});
});
describe("CliCommand", () => {
let cliCommand: CliCommand;
let cliCommand: CliCommand;
beforeEach(() => {
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
},
{
name: "arg2",
shortName: "a",
type: CliParameterType.NUMBER,
needsValue: true,
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
],
() => {
// Do nothing
}
);
});
beforeEach(() => {
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
},
{
name: "arg2",
shortName: "a",
type: CliParameterType.NUMBER,
needsValue: true,
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
],
() => {
// Do nothing
},
);
});
it("should parse string arguments correctly", () => {
const args = cliCommand["parseArgs"]([
"--arg1",
"value1",
"--arg2",
"42",
"--arg3",
"--arg4",
"value1,value2",
]);
expect(args).toEqual({
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
});
});
it("should parse string arguments correctly", () => {
// @ts-expect-error Testing private method
const args = cliCommand.parseArgs([
"--arg1",
"value1",
"--arg2",
"42",
"--arg3",
"--arg4",
"value1,value2",
]);
expect(args).toEqual({
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
});
});
it("should parse short names for arguments too", () => {
const args = cliCommand["parseArgs"]([
"--arg1",
"value1",
"-a",
"42",
"--arg3",
"--arg4",
"value1,value2",
]);
expect(args).toEqual({
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
});
});
it("should parse short names for arguments too", () => {
// @ts-expect-error Testing private method
const args = cliCommand.parseArgs([
"--arg1",
"value1",
"-a",
"42",
"--arg3",
"--arg4",
"value1,value2",
]);
expect(args).toEqual({
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
});
});
it("should cast argument values correctly", () => {
expect(cliCommand["castArgValue"]("42", CliParameterType.NUMBER)).toBe(
42
);
expect(
cliCommand["castArgValue"]("true", CliParameterType.BOOLEAN)
).toBe(true);
expect(
cliCommand["castArgValue"]("value1,value2", CliParameterType.ARRAY)
).toEqual(["value1", "value2"]);
});
it("should cast argument values correctly", () => {
// @ts-expect-error Testing private method
expect(cliCommand.castArgValue("42", CliParameterType.NUMBER)).toBe(42);
// @ts-expect-error Testing private method
expect(cliCommand.castArgValue("true", CliParameterType.BOOLEAN)).toBe(
true,
);
expect(
// @ts-expect-error Testing private method
cliCommand.castArgValue("value1,value2", CliParameterType.ARRAY),
).toEqual(["value1", "value2"]);
});
it("should run the execute function with the parsed parameters", async () => {
const mockExecute = jest.fn();
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
},
{
name: "arg2",
type: CliParameterType.NUMBER,
needsValue: true,
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
],
mockExecute
);
it("should run the execute function with the parsed parameters", async () => {
const mockExecute = jest.fn();
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
},
{
name: "arg2",
type: CliParameterType.NUMBER,
needsValue: true,
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
],
mockExecute,
);
await cliCommand.run([
"--arg1",
"value1",
"--arg2",
"42",
"--arg3",
"--arg4",
"value1,value2",
]);
expect(mockExecute).toHaveBeenCalledWith(cliCommand, {
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
});
});
await cliCommand.run([
"--arg1",
"value1",
"--arg2",
"42",
"--arg3",
"--arg4",
"value1,value2",
]);
expect(mockExecute).toHaveBeenCalledWith(cliCommand, {
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
});
});
it("should work with a mix of positioned and non-positioned arguments", async () => {
const mockExecute = jest.fn();
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
},
{
name: "arg2",
type: CliParameterType.NUMBER,
needsValue: true,
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
{
name: "arg5",
type: CliParameterType.STRING,
needsValue: true,
positioned: true,
},
],
mockExecute
);
it("should work with a mix of positioned and non-positioned arguments", async () => {
const mockExecute = jest.fn();
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
},
{
name: "arg2",
type: CliParameterType.NUMBER,
needsValue: true,
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
{
name: "arg5",
type: CliParameterType.STRING,
needsValue: true,
positioned: true,
},
],
mockExecute,
);
await cliCommand.run([
"--arg1",
"value1",
"--arg2",
"42",
"--arg3",
"--arg4",
"value1,value2",
"value5",
]);
await cliCommand.run([
"--arg1",
"value1",
"--arg2",
"42",
"--arg3",
"--arg4",
"value1,value2",
"value5",
]);
expect(mockExecute).toHaveBeenCalledWith(cliCommand, {
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
arg5: "value5",
});
});
expect(mockExecute).toHaveBeenCalledWith(cliCommand, {
arg1: "value1",
arg2: 42,
arg3: true,
arg4: ["value1", "value2"],
arg5: "value5",
});
});
it("should display help message correctly", () => {
const consoleLogSpy = spyOn(console, "log").mockImplementation(() => {
// Do nothing
});
it("should display help message correctly", () => {
const consoleLogSpy = spyOn(console, "log").mockImplementation(() => {
// Do nothing
});
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
description: "Argument 1",
optional: true,
},
{
name: "arg2",
type: CliParameterType.NUMBER,
needsValue: true,
description: "Argument 2",
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
description: "Argument 3",
optional: true,
positioned: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
description: "Argument 4",
positioned: false,
},
],
() => {
// Do nothing
},
"This is a test command",
"category1 category2 --arg1 value1 --arg2 42 arg3 --arg4 value1,value2"
);
cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
description: "Argument 1",
optional: true,
},
{
name: "arg2",
type: CliParameterType.NUMBER,
needsValue: true,
description: "Argument 2",
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
description: "Argument 3",
optional: true,
positioned: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
description: "Argument 4",
positioned: false,
},
],
() => {
// Do nothing
},
"This is a test command",
"category1 category2 --arg1 value1 --arg2 42 arg3 --arg4 value1,value2",
);
cliCommand.displayHelp();
cliCommand.displayHelp();
const loggedString = consoleLogSpy.mock.calls.map(call =>
stripAnsi(call[0])
)[0];
const loggedString = consoleLogSpy.mock.calls.map((call) =>
stripAnsi(call[0]),
)[0];
consoleLogSpy.mockRestore();
consoleLogSpy.mockRestore();
expect(loggedString).toContain("📚 Command: category1 category2");
expect(loggedString).toContain("🔧 Arguments:");
expect(loggedString).toContain("arg1: Argument 1 (optional)");
expect(loggedString).toContain("arg2: Argument 2");
expect(loggedString).toContain("--arg3: Argument 3 (optional)");
expect(loggedString).toContain("--arg4: Argument 4");
expect(loggedString).toContain("🚀 Example:");
expect(loggedString).toContain(
"category1 category2 --arg1 value1 --arg2 42 arg3 --arg4 value1,value2"
);
});
expect(loggedString).toContain("📚 Command: category1 category2");
expect(loggedString).toContain("🔧 Arguments:");
expect(loggedString).toContain("arg1: Argument 1 (optional)");
expect(loggedString).toContain("arg2: Argument 2");
expect(loggedString).toContain("--arg3: Argument 3 (optional)");
expect(loggedString).toContain("--arg4: Argument 4");
expect(loggedString).toContain("🚀 Example:");
expect(loggedString).toContain(
"category1 category2 --arg1 value1 --arg2 42 arg3 --arg4 value1,value2",
);
});
});
describe("CliBuilder", () => {
let cliBuilder: CliBuilder;
let mockCommand1: CliCommand;
let mockCommand2: CliCommand;
let cliBuilder: CliBuilder;
let mockCommand1: CliCommand;
let mockCommand2: CliCommand;
beforeEach(() => {
mockCommand1 = new CliCommand(["category1"], [], jest.fn());
mockCommand2 = new CliCommand(["category2"], [], jest.fn());
cliBuilder = new CliBuilder([mockCommand1]);
});
beforeEach(() => {
mockCommand1 = new CliCommand(["category1"], [], jest.fn());
mockCommand2 = new CliCommand(["category2"], [], jest.fn());
cliBuilder = new CliBuilder([mockCommand1]);
});
it("should register a command correctly", () => {
cliBuilder.registerCommand(mockCommand2);
expect(cliBuilder.commands).toContain(mockCommand2);
});
it("should register a command correctly", () => {
cliBuilder.registerCommand(mockCommand2);
expect(cliBuilder.commands).toContain(mockCommand2);
});
it("should register multiple commands correctly", () => {
const mockCommand3 = new CliCommand(["category3"], [], jest.fn());
cliBuilder.registerCommands([mockCommand2, mockCommand3]);
expect(cliBuilder.commands).toContain(mockCommand2);
expect(cliBuilder.commands).toContain(mockCommand3);
});
it("should register multiple commands correctly", () => {
const mockCommand3 = new CliCommand(["category3"], [], jest.fn());
cliBuilder.registerCommands([mockCommand2, mockCommand3]);
expect(cliBuilder.commands).toContain(mockCommand2);
expect(cliBuilder.commands).toContain(mockCommand3);
});
it("should error when adding duplicates", () => {
expect(() => {
cliBuilder.registerCommand(mockCommand1);
}).toThrow();
it("should error when adding duplicates", () => {
expect(() => {
cliBuilder.registerCommand(mockCommand1);
}).toThrow();
expect(() => {
cliBuilder.registerCommands([mockCommand1]);
}).toThrow();
});
expect(() => {
cliBuilder.registerCommands([mockCommand1]);
}).toThrow();
});
it("should deregister a command correctly", () => {
cliBuilder.deregisterCommand(mockCommand1);
expect(cliBuilder.commands).not.toContain(mockCommand1);
});
it("should deregister a command correctly", () => {
cliBuilder.deregisterCommand(mockCommand1);
expect(cliBuilder.commands).not.toContain(mockCommand1);
});
it("should deregister multiple commands correctly", () => {
cliBuilder.registerCommand(mockCommand2);
cliBuilder.deregisterCommands([mockCommand1, mockCommand2]);
expect(cliBuilder.commands).not.toContain(mockCommand1);
expect(cliBuilder.commands).not.toContain(mockCommand2);
});
it("should deregister multiple commands correctly", () => {
cliBuilder.registerCommand(mockCommand2);
cliBuilder.deregisterCommands([mockCommand1, mockCommand2]);
expect(cliBuilder.commands).not.toContain(mockCommand1);
expect(cliBuilder.commands).not.toContain(mockCommand2);
});
it("should process args correctly", async () => {
const mockExecute = jest.fn();
const mockCommand = new CliCommand(
["category1", "sub1"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
positioned: false,
},
],
mockExecute
);
cliBuilder.registerCommand(mockCommand);
await cliBuilder.processArgs([
"./cli.ts",
"category1",
"sub1",
"--arg1",
"value1",
]);
expect(mockExecute).toHaveBeenCalledWith(expect.anything(), {
arg1: "value1",
});
});
it("should process args correctly", async () => {
const mockExecute = jest.fn();
const mockCommand = new CliCommand(
["category1", "sub1"],
[
{
name: "arg1",
type: CliParameterType.STRING,
needsValue: true,
positioned: false,
},
],
mockExecute,
);
cliBuilder.registerCommand(mockCommand);
await cliBuilder.processArgs([
"./cli.ts",
"category1",
"sub1",
"--arg1",
"value1",
]);
expect(mockExecute).toHaveBeenCalledWith(expect.anything(), {
arg1: "value1",
});
});
describe("should build command tree", () => {
let cliBuilder: CliBuilder;
let mockCommand1: CliCommand;
let mockCommand2: CliCommand;
let mockCommand3: CliCommand;
let mockCommand4: CliCommand;
let mockCommand5: CliCommand;
describe("should build command tree", () => {
let cliBuilder: CliBuilder;
let mockCommand1: CliCommand;
let mockCommand2: CliCommand;
let mockCommand3: CliCommand;
let mockCommand4: CliCommand;
let mockCommand5: CliCommand;
beforeEach(() => {
mockCommand1 = new CliCommand(["user", "verify"], [], jest.fn());
mockCommand2 = new CliCommand(["user", "delete"], [], jest.fn());
mockCommand3 = new CliCommand(
["user", "new", "admin"],
[],
jest.fn()
);
mockCommand4 = new CliCommand(["user", "new"], [], jest.fn());
mockCommand5 = new CliCommand(["admin", "delete"], [], jest.fn());
cliBuilder = new CliBuilder([
mockCommand1,
mockCommand2,
mockCommand3,
mockCommand4,
mockCommand5,
]);
});
beforeEach(() => {
mockCommand1 = new CliCommand(["user", "verify"], [], jest.fn());
mockCommand2 = new CliCommand(["user", "delete"], [], jest.fn());
mockCommand3 = new CliCommand(
["user", "new", "admin"],
[],
jest.fn(),
);
mockCommand4 = new CliCommand(["user", "new"], [], jest.fn());
mockCommand5 = new CliCommand(["admin", "delete"], [], jest.fn());
cliBuilder = new CliBuilder([
mockCommand1,
mockCommand2,
mockCommand3,
mockCommand4,
mockCommand5,
]);
});
it("should build the command tree correctly", () => {
const tree = cliBuilder.getCommandTree(cliBuilder.commands);
expect(tree).toEqual({
user: {
verify: mockCommand1,
delete: mockCommand2,
new: {
admin: mockCommand3,
},
},
admin: {
delete: mockCommand5,
},
});
});
it("should build the command tree correctly", () => {
const tree = cliBuilder.getCommandTree(cliBuilder.commands);
expect(tree).toEqual({
user: {
verify: mockCommand1,
delete: mockCommand2,
new: {
admin: mockCommand3,
},
},
admin: {
delete: mockCommand5,
},
});
});
it("should build the command tree correctly when there are no commands", () => {
cliBuilder = new CliBuilder([]);
const tree = cliBuilder.getCommandTree(cliBuilder.commands);
expect(tree).toEqual({});
});
it("should build the command tree correctly when there are no commands", () => {
cliBuilder = new CliBuilder([]);
const tree = cliBuilder.getCommandTree(cliBuilder.commands);
expect(tree).toEqual({});
});
it("should build the command tree correctly when there is only one command", () => {
cliBuilder = new CliBuilder([mockCommand1]);
const tree = cliBuilder.getCommandTree(cliBuilder.commands);
expect(tree).toEqual({
user: {
verify: mockCommand1,
},
});
});
});
it("should build the command tree correctly when there is only one command", () => {
cliBuilder = new CliBuilder([mockCommand1]);
const tree = cliBuilder.getCommandTree(cliBuilder.commands);
expect(tree).toEqual({
user: {
verify: mockCommand1,
},
});
});
});
it("should show help menu", () => {
const consoleLogSpy = spyOn(console, "log").mockImplementation(() => {
// Do nothing
});
it("should show help menu", () => {
const consoleLogSpy = spyOn(console, "log").mockImplementation(() => {
// Do nothing
});
const cliBuilder = new CliBuilder();
const cliBuilder = new CliBuilder();
const cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "name",
type: CliParameterType.STRING,
needsValue: true,
description: "Name of new item",
},
{
name: "delete-previous",
type: CliParameterType.NUMBER,
needsValue: false,
positioned: false,
optional: true,
description: "Also delete the previous item",
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
],
() => {
// Do nothing
},
"I love sussy sauces",
"emoji add --url https://site.com/image.png"
);
const cliCommand = new CliCommand(
["category1", "category2"],
[
{
name: "name",
type: CliParameterType.STRING,
needsValue: true,
description: "Name of new item",
},
{
name: "delete-previous",
type: CliParameterType.NUMBER,
needsValue: false,
positioned: false,
optional: true,
description: "Also delete the previous item",
},
{
name: "arg3",
type: CliParameterType.BOOLEAN,
needsValue: false,
},
{
name: "arg4",
type: CliParameterType.ARRAY,
needsValue: true,
},
],
() => {
// Do nothing
},
"I love sussy sauces",
"emoji add --url https://site.com/image.png",
);
cliBuilder.registerCommand(cliCommand);
cliBuilder.displayHelp();
cliBuilder.registerCommand(cliCommand);
cliBuilder.displayHelp();
const loggedString = consoleLogSpy.mock.calls
.map(call => stripAnsi(call[0]))
.join("\n");
const loggedString = consoleLogSpy.mock.calls
.map((call) => stripAnsi(call[0]))
.join("\n");
consoleLogSpy.mockRestore();
consoleLogSpy.mockRestore();
expect(loggedString).toContain("category1");
expect(loggedString).toContain(
" category2.................I love sussy sauces"
);
expect(loggedString).toContain(
" name..................Name of new item"
);
expect(loggedString).toContain(
" arg3..................(no description)"
);
expect(loggedString).toContain(
" arg4..................(no description)"
);
expect(loggedString).toContain(
" --delete-previous.....Also delete the previous item (optional)"
);
expect(loggedString).toContain(
" Example: emoji add --url https://site.com/image.png"
);
});
expect(loggedString).toContain("category1");
expect(loggedString).toContain(
" category2.................I love sussy sauces",
);
expect(loggedString).toContain(
" name..................Name of new item",
);
expect(loggedString).toContain(
" arg3..................(no description)",
);
expect(loggedString).toContain(
" arg4..................(no description)",
);
expect(loggedString).toContain(
" --delete-previous.....Also delete the previous item (optional)",
);
expect(loggedString).toContain(
" Example: emoji add --url https://site.com/image.png",
);
});
});

File diff suppressed because it is too large Load diff

View file

@ -6,18 +6,18 @@
*/
import { watchConfig } from "c12";
import { defaultConfig, type Config } from "./config.type";
import { type Config, defaultConfig } from "./config.type";
const { config } = await watchConfig<Config>({
configFile: "./config/config.toml",
defaultConfig: defaultConfig,
overrides:
(
await watchConfig<Config>({
configFile: "./config/config.internal.toml",
defaultConfig: {} as Config,
})
).config ?? undefined,
configFile: "./config/config.toml",
defaultConfig: defaultConfig,
overrides:
(
await watchConfig<Config>({
configFile: "./config/config.internal.toml",
defaultConfig: {} as Config,
})
).config ?? undefined,
});
const exportedConfig = config ?? defaultConfig;

View file

@ -1,6 +1,6 @@
{
"name": "config-manager",
"version": "0.0.0",
"main": "index.ts",
"dependencies": { "@iarna/toml": "^2.2.5", "merge-deep-ts": "^1.2.6" }
"name": "config-manager",
"version": "0.0.0",
"main": "index.ts",
"dependencies": { "@iarna/toml": "^2.2.5", "merge-deep-ts": "^1.2.6" }
}

View file

@ -1,12 +1,12 @@
import { appendFile } from "node:fs/promises";
import type { BunFile } from "bun";
import { appendFile } from "fs/promises";
export enum LogLevel {
DEBUG = "debug",
INFO = "info",
WARNING = "warning",
ERROR = "error",
CRITICAL = "critical",
DEBUG = "debug",
INFO = "info",
WARNING = "warning",
ERROR = "error",
CRITICAL = "critical",
}
/**
@ -14,161 +14,165 @@ export enum LogLevel {
* @param output BunFile of output (can be a normal file or something like Bun.stdout)
*/
export class LogManager {
constructor(private output: BunFile) {
void this.write(
`--- INIT LogManager at ${new Date().toISOString()} ---`
);
}
constructor(private output: BunFile) {
void this.write(
`--- INIT LogManager at ${new Date().toISOString()} ---`,
);
}
/**
* Logs a message to the output
* @param level Importance of the log
* @param entity Emitter of the log
* @param message Message to log
* @param showTimestamp Whether to show the timestamp in the log
*/
async log(
level: LogLevel,
entity: string,
message: string,
showTimestamp = true
) {
await this.write(
`${showTimestamp ? new Date().toISOString() + " " : ""}[${level.toUpperCase()}] ${entity}: ${message}`
);
}
/**
* Logs a message to the output
* @param level Importance of the log
* @param entity Emitter of the log
* @param message Message to log
* @param showTimestamp Whether to show the timestamp in the log
*/
async log(
level: LogLevel,
entity: string,
message: string,
showTimestamp = true,
) {
await this.write(
`${
showTimestamp ? `${new Date().toISOString()} ` : ""
}[${level.toUpperCase()}] ${entity}: ${message}`,
);
}
private async write(text: string) {
if (this.output == Bun.stdout) {
await Bun.write(Bun.stdout, text + "\n");
} else {
if (!(await this.output.exists())) {
// Create file if it doesn't exist
await Bun.write(this.output, "", {
createPath: true,
});
}
await appendFile(this.output.name ?? "", text + "\n");
}
}
private async write(text: string) {
if (this.output === Bun.stdout) {
await Bun.write(Bun.stdout, `${text}\n`);
} else {
if (!(await this.output.exists())) {
// Create file if it doesn't exist
await Bun.write(this.output, "", {
createPath: true,
});
}
await appendFile(this.output.name ?? "", `${text}\n`);
}
}
/**
* Logs an error to the output, wrapper for log
* @param level Importance of the log
* @param entity Emitter of the log
* @param error Error to log
*/
async logError(level: LogLevel, entity: string, error: Error) {
await this.log(level, entity, error.message);
}
/**
* Logs an error to the output, wrapper for log
* @param level Importance of the log
* @param entity Emitter of the log
* @param error Error to log
*/
async logError(level: LogLevel, entity: string, error: Error) {
await this.log(level, entity, error.message);
}
/**
* Logs a request to the output
* @param req Request to log
* @param ip IP of the request
* @param logAllDetails Whether to log all details of the request
*/
async logRequest(req: Request, ip?: string, logAllDetails = false) {
let string = ip ? `${ip}: ` : "";
/**
* Logs a request to the output
* @param req Request to log
* @param ip IP of the request
* @param logAllDetails Whether to log all details of the request
*/
async logRequest(req: Request, ip?: string, logAllDetails = false) {
let string = ip ? `${ip}: ` : "";
string += `${req.method} ${req.url}`;
string += `${req.method} ${req.url}`;
if (logAllDetails) {
string += `\n`;
string += ` [Headers]\n`;
// Pretty print headers
for (const [key, value] of req.headers.entries()) {
string += ` ${key}: ${value}\n`;
}
if (logAllDetails) {
string += "\n";
string += " [Headers]\n";
// Pretty print headers
for (const [key, value] of req.headers.entries()) {
string += ` ${key}: ${value}\n`;
}
// Pretty print body
string += ` [Body]\n`;
const content_type = req.headers.get("Content-Type");
// Pretty print body
string += " [Body]\n";
const content_type = req.headers.get("Content-Type");
if (content_type && content_type.includes("application/json")) {
const json = await req.json();
const stringified = JSON.stringify(json, null, 4)
.split("\n")
.map(line => ` ${line}`)
.join("\n");
if (content_type?.includes("application/json")) {
const json = await req.json();
const stringified = JSON.stringify(json, null, 4)
.split("\n")
.map((line) => ` ${line}`)
.join("\n");
string += `${stringified}\n`;
} else if (
content_type &&
(content_type.includes("application/x-www-form-urlencoded") ||
content_type.includes("multipart/form-data"))
) {
const formData = await req.formData();
for (const [key, value] of formData.entries()) {
if (value.toString().length < 300) {
string += ` ${key}: ${value.toString()}\n`;
} else {
string += ` ${key}: <${value.toString().length} bytes>\n`;
}
}
} else {
const text = await req.text();
string += ` ${text}\n`;
}
}
await this.log(LogLevel.INFO, "Request", string);
}
string += `${stringified}\n`;
} else if (
content_type &&
(content_type.includes("application/x-www-form-urlencoded") ||
content_type.includes("multipart/form-data"))
) {
const formData = await req.formData();
for (const [key, value] of formData.entries()) {
if (value.toString().length < 300) {
string += ` ${key}: ${value.toString()}\n`;
} else {
string += ` ${key}: <${
value.toString().length
} bytes>\n`;
}
}
} else {
const text = await req.text();
string += ` ${text}\n`;
}
}
await this.log(LogLevel.INFO, "Request", string);
}
}
/**
* Outputs to multiple LogManager instances at once
*/
export class MultiLogManager {
constructor(private logManagers: LogManager[]) {}
constructor(private logManagers: LogManager[]) {}
/**
* Logs a message to all logManagers
* @param level Importance of the log
* @param entity Emitter of the log
* @param message Message to log
* @param showTimestamp Whether to show the timestamp in the log
*/
async log(
level: LogLevel,
entity: string,
message: string,
showTimestamp = true
) {
for (const logManager of this.logManagers) {
await logManager.log(level, entity, message, showTimestamp);
}
}
/**
* Logs a message to all logManagers
* @param level Importance of the log
* @param entity Emitter of the log
* @param message Message to log
* @param showTimestamp Whether to show the timestamp in the log
*/
async log(
level: LogLevel,
entity: string,
message: string,
showTimestamp = true,
) {
for (const logManager of this.logManagers) {
await logManager.log(level, entity, message, showTimestamp);
}
}
/**
* Logs an error to all logManagers
* @param level Importance of the log
* @param entity Emitter of the log
* @param error Error to log
*/
async logError(level: LogLevel, entity: string, error: Error) {
for (const logManager of this.logManagers) {
await logManager.logError(level, entity, error);
}
}
/**
* Logs an error to all logManagers
* @param level Importance of the log
* @param entity Emitter of the log
* @param error Error to log
*/
async logError(level: LogLevel, entity: string, error: Error) {
for (const logManager of this.logManagers) {
await logManager.logError(level, entity, error);
}
}
/**
* Logs a request to all logManagers
* @param req Request to log
* @param ip IP of the request
* @param logAllDetails Whether to log all details of the request
*/
async logRequest(req: Request, ip?: string, logAllDetails = false) {
for (const logManager of this.logManagers) {
await logManager.logRequest(req, ip, logAllDetails);
}
}
/**
* Logs a request to all logManagers
* @param req Request to log
* @param ip IP of the request
* @param logAllDetails Whether to log all details of the request
*/
async logRequest(req: Request, ip?: string, logAllDetails = false) {
for (const logManager of this.logManagers) {
await logManager.logRequest(req, ip, logAllDetails);
}
}
/**
* Create a MultiLogManager from multiple LogManager instances
* @param logManagers LogManager instances to use
* @returns
*/
static fromLogManagers(...logManagers: LogManager[]) {
return new MultiLogManager(logManagers);
}
/**
* Create a MultiLogManager from multiple LogManager instances
* @param logManagers LogManager instances to use
* @returns
*/
static fromLogManagers(...logManagers: LogManager[]) {
return new MultiLogManager(logManagers);
}
}

View file

@ -2,5 +2,5 @@
"name": "log-manager",
"version": "0.0.0",
"main": "index.ts",
"dependencies": { }
}
"dependencies": {}
}

View file

@ -1,117 +1,117 @@
// FILEPATH: /home/jessew/Dev/lysand/packages/log-manager/log-manager.test.ts
import { LogManager, LogLevel, MultiLogManager } from "../index";
import type fs from "fs/promises";
import {
describe,
it,
beforeEach,
expect,
jest,
mock,
type Mock,
test,
type Mock,
beforeEach,
describe,
expect,
it,
jest,
mock,
test,
} from "bun:test";
import type fs from "node:fs/promises";
import type { BunFile } from "bun";
// FILEPATH: /home/jessew/Dev/lysand/packages/log-manager/log-manager.test.ts
import { LogLevel, LogManager, MultiLogManager } from "../index";
describe("LogManager", () => {
let logManager: LogManager;
let mockOutput: BunFile;
let mockAppend: Mock<typeof fs.appendFile>;
let logManager: LogManager;
let mockOutput: BunFile;
let mockAppend: Mock<typeof fs.appendFile>;
beforeEach(async () => {
mockOutput = Bun.file("test.log");
mockAppend = jest.fn();
await mock.module("fs/promises", () => ({
appendFile: mockAppend,
}));
logManager = new LogManager(mockOutput);
});
beforeEach(async () => {
mockOutput = Bun.file("test.log");
mockAppend = jest.fn();
await mock.module("fs/promises", () => ({
appendFile: mockAppend,
}));
logManager = new LogManager(mockOutput);
});
it("should initialize and write init log", () => {
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("--- INIT LogManager at")
);
});
it("should initialize and write init log", () => {
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("--- INIT LogManager at"),
);
});
it("should log message with timestamp", async () => {
await logManager.log(LogLevel.INFO, "TestEntity", "Test message");
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("[INFO] TestEntity: Test message")
);
});
it("should log message with timestamp", async () => {
await logManager.log(LogLevel.INFO, "TestEntity", "Test message");
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("[INFO] TestEntity: Test message"),
);
});
it("should log message without timestamp", async () => {
await logManager.log(
LogLevel.INFO,
"TestEntity",
"Test message",
false
);
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
"[INFO] TestEntity: Test message\n"
);
});
it("should log message without timestamp", async () => {
await logManager.log(
LogLevel.INFO,
"TestEntity",
"Test message",
false,
);
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
"[INFO] TestEntity: Test message\n",
);
});
test.skip("should write to stdout", async () => {
logManager = new LogManager(Bun.stdout);
await logManager.log(LogLevel.INFO, "TestEntity", "Test message");
test.skip("should write to stdout", async () => {
logManager = new LogManager(Bun.stdout);
await logManager.log(LogLevel.INFO, "TestEntity", "Test message");
const writeMock = jest.fn();
const writeMock = jest.fn();
await mock.module("Bun", () => ({
stdout: Bun.stdout,
write: writeMock,
}));
await mock.module("Bun", () => ({
stdout: Bun.stdout,
write: writeMock,
}));
expect(writeMock).toHaveBeenCalledWith(
Bun.stdout,
expect.stringContaining("[INFO] TestEntity: Test message")
);
});
expect(writeMock).toHaveBeenCalledWith(
Bun.stdout,
expect.stringContaining("[INFO] TestEntity: Test message"),
);
});
it("should throw error if output file does not exist", () => {
mockAppend.mockImplementationOnce(() => {
return Promise.reject(
new Error("Output file doesnt exist (and isnt stdout)")
);
});
expect(
logManager.log(LogLevel.INFO, "TestEntity", "Test message")
).rejects.toThrow(Error);
});
it("should throw error if output file does not exist", () => {
mockAppend.mockImplementationOnce(() => {
return Promise.reject(
new Error("Output file doesnt exist (and isnt stdout)"),
);
});
expect(
logManager.log(LogLevel.INFO, "TestEntity", "Test message"),
).rejects.toThrow(Error);
});
it("should log error message", async () => {
const error = new Error("Test error");
await logManager.logError(LogLevel.ERROR, "TestEntity", error);
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("[ERROR] TestEntity: Test error")
);
});
it("should log error message", async () => {
const error = new Error("Test error");
await logManager.logError(LogLevel.ERROR, "TestEntity", error);
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("[ERROR] TestEntity: Test error"),
);
});
it("should log basic request details", async () => {
const req = new Request("http://localhost/test", { method: "GET" });
await logManager.logRequest(req, "127.0.0.1");
it("should log basic request details", async () => {
const req = new Request("http://localhost/test", { method: "GET" });
await logManager.logRequest(req, "127.0.0.1");
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("127.0.0.1: GET http://localhost/test")
);
});
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining("127.0.0.1: GET http://localhost/test"),
);
});
describe("Request logger", () => {
it("should log all request details for JSON content type", async () => {
const req = new Request("http://localhost/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ test: "value" }),
});
await logManager.logRequest(req, "127.0.0.1", true);
describe("Request logger", () => {
it("should log all request details for JSON content type", async () => {
const req = new Request("http://localhost/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ test: "value" }),
});
await logManager.logRequest(req, "127.0.0.1", true);
const expectedLog = `127.0.0.1: POST http://localhost/test
const expectedLog = `127.0.0.1: POST http://localhost/test
[Headers]
content-type: application/json
[Body]
@ -120,112 +120,112 @@ describe("LogManager", () => {
}
`;
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining(expectedLog)
);
});
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining(expectedLog),
);
});
it("should log all request details for text content type", async () => {
const req = new Request("http://localhost/test", {
method: "POST",
headers: { "Content-Type": "text/plain" },
body: "Test body",
});
await logManager.logRequest(req, "127.0.0.1", true);
it("should log all request details for text content type", async () => {
const req = new Request("http://localhost/test", {
method: "POST",
headers: { "Content-Type": "text/plain" },
body: "Test body",
});
await logManager.logRequest(req, "127.0.0.1", true);
const expectedLog = `127.0.0.1: POST http://localhost/test
const expectedLog = `127.0.0.1: POST http://localhost/test
[Headers]
content-type: text/plain
[Body]
Test body
`;
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining(expectedLog)
);
});
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining(expectedLog),
);
});
it("should log all request details for FormData content-type", async () => {
const formData = new FormData();
formData.append("test", "value");
const req = new Request("http://localhost/test", {
method: "POST",
body: formData,
});
await logManager.logRequest(req, "127.0.0.1", true);
it("should log all request details for FormData content-type", async () => {
const formData = new FormData();
formData.append("test", "value");
const req = new Request("http://localhost/test", {
method: "POST",
body: formData,
});
await logManager.logRequest(req, "127.0.0.1", true);
const expectedLog = `127.0.0.1: POST http://localhost/test
const expectedLog = `127.0.0.1: POST http://localhost/test
[Headers]
content-type: multipart/form-data; boundary=${
req.headers.get("Content-Type")?.split("boundary=")[1] ?? ""
}
req.headers.get("Content-Type")?.split("boundary=")[1] ?? ""
}
[Body]
test: value
`;
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining(
expectedLog.replace("----", expect.any(String))
)
);
});
});
expect(mockAppend).toHaveBeenCalledWith(
mockOutput.name,
expect.stringContaining(
expectedLog.replace("----", expect.any(String)),
),
);
});
});
});
describe("MultiLogManager", () => {
let multiLogManager: MultiLogManager;
let mockLogManagers: LogManager[];
let mockLog: jest.Mock;
let mockLogError: jest.Mock;
let mockLogRequest: jest.Mock;
let multiLogManager: MultiLogManager;
let mockLogManagers: LogManager[];
let mockLog: jest.Mock;
let mockLogError: jest.Mock;
let mockLogRequest: jest.Mock;
beforeEach(() => {
mockLog = jest.fn();
mockLogError = jest.fn();
mockLogRequest = jest.fn();
mockLogManagers = [
{
log: mockLog,
logError: mockLogError,
logRequest: mockLogRequest,
},
{
log: mockLog,
logError: mockLogError,
logRequest: mockLogRequest,
},
] as unknown as LogManager[];
multiLogManager = MultiLogManager.fromLogManagers(...mockLogManagers);
});
beforeEach(() => {
mockLog = jest.fn();
mockLogError = jest.fn();
mockLogRequest = jest.fn();
mockLogManagers = [
{
log: mockLog,
logError: mockLogError,
logRequest: mockLogRequest,
},
{
log: mockLog,
logError: mockLogError,
logRequest: mockLogRequest,
},
] as unknown as LogManager[];
multiLogManager = MultiLogManager.fromLogManagers(...mockLogManagers);
});
it("should log message to all logManagers", async () => {
await multiLogManager.log(LogLevel.INFO, "TestEntity", "Test message");
expect(mockLog).toHaveBeenCalledTimes(2);
expect(mockLog).toHaveBeenCalledWith(
LogLevel.INFO,
"TestEntity",
"Test message",
true
);
});
it("should log message to all logManagers", async () => {
await multiLogManager.log(LogLevel.INFO, "TestEntity", "Test message");
expect(mockLog).toHaveBeenCalledTimes(2);
expect(mockLog).toHaveBeenCalledWith(
LogLevel.INFO,
"TestEntity",
"Test message",
true,
);
});
it("should log error to all logManagers", async () => {
const error = new Error("Test error");
await multiLogManager.logError(LogLevel.ERROR, "TestEntity", error);
expect(mockLogError).toHaveBeenCalledTimes(2);
expect(mockLogError).toHaveBeenCalledWith(
LogLevel.ERROR,
"TestEntity",
error
);
});
it("should log error to all logManagers", async () => {
const error = new Error("Test error");
await multiLogManager.logError(LogLevel.ERROR, "TestEntity", error);
expect(mockLogError).toHaveBeenCalledTimes(2);
expect(mockLogError).toHaveBeenCalledWith(
LogLevel.ERROR,
"TestEntity",
error,
);
});
it("should log request to all logManagers", async () => {
const req = new Request("http://localhost/test", { method: "GET" });
await multiLogManager.logRequest(req, "127.0.0.1", true);
expect(mockLogRequest).toHaveBeenCalledTimes(2);
expect(mockLogRequest).toHaveBeenCalledWith(req, "127.0.0.1", true);
});
it("should log request to all logManagers", async () => {
const req = new Request("http://localhost/test", { method: "GET" });
await multiLogManager.logRequest(req, "127.0.0.1", true);
expect(mockLogRequest).toHaveBeenCalledTimes(2);
expect(mockLogRequest).toHaveBeenCalledWith(req, "127.0.0.1", true);
});
});

View file

@ -1,64 +1,65 @@
import type { Config } from "config-manager";
import { MediaBackend, MediaBackendType, MediaHasher } from "..";
import type { ConvertableMediaFormats } from "../media-converter";
import { MediaConverter } from "../media-converter";
import { MediaBackend, MediaBackendType, MediaHasher } from "..";
import type { ConfigType } from "config-manager";
export class LocalMediaBackend extends MediaBackend {
constructor(config: ConfigType) {
super(config, MediaBackendType.LOCAL);
}
constructor(config: Config) {
super(config, MediaBackendType.LOCAL);
}
public async addFile(file: File) {
if (this.shouldConvertImages(this.config)) {
const fileExtension = file.name.split(".").pop();
const mediaConverter = new MediaConverter(
fileExtension as ConvertableMediaFormats,
this.config.media.conversion
.convert_to as ConvertableMediaFormats
);
file = await mediaConverter.convert(file);
}
public async addFile(file: File) {
let convertedFile = file;
if (this.shouldConvertImages(this.config)) {
const fileExtension = file.name.split(".").pop();
const mediaConverter = new MediaConverter(
fileExtension as ConvertableMediaFormats,
this.config.media.conversion
.convert_to as ConvertableMediaFormats,
);
convertedFile = await mediaConverter.convert(file);
}
const hash = await new MediaHasher().getMediaHash(file);
const hash = await new MediaHasher().getMediaHash(convertedFile);
const newFile = Bun.file(
`${this.config.media.local_uploads_folder}/${hash}`
);
const newFile = Bun.file(
`${this.config.media.local_uploads_folder}/${hash}`,
);
if (await newFile.exists()) {
throw new Error("File already exists");
}
if (await newFile.exists()) {
throw new Error("File already exists");
}
await Bun.write(newFile, file);
await Bun.write(newFile, convertedFile);
return {
uploadedFile: file,
path: `./uploads/${file.name}`,
hash: hash,
};
}
return {
uploadedFile: convertedFile,
path: `./uploads/${convertedFile.name}`,
hash: hash,
};
}
public async getFileByHash(
hash: string,
databaseHashFetcher: (sha256: string) => Promise<string | null>
): Promise<File | null> {
const filename = await databaseHashFetcher(hash);
public async getFileByHash(
hash: string,
databaseHashFetcher: (sha256: string) => Promise<string | null>,
): Promise<File | null> {
const filename = await databaseHashFetcher(hash);
if (!filename) return null;
if (!filename) return null;
return this.getFile(filename);
}
return this.getFile(filename);
}
public async getFile(filename: string): Promise<File | null> {
const file = Bun.file(
`${this.config.media.local_uploads_folder}/${filename}`
);
public async getFile(filename: string): Promise<File | null> {
const file = Bun.file(
`${this.config.media.local_uploads_folder}/${filename}`,
);
if (!(await file.exists())) return null;
if (!(await file.exists())) return null;
return new File([await file.arrayBuffer()], filename, {
type: file.type,
lastModified: file.lastModified,
});
}
return new File([await file.arrayBuffer()], filename, {
type: file.type,
lastModified: file.lastModified,
});
}
}

View file

@ -1,69 +1,74 @@
import { S3Client } from "@jsr/bradenmacdonald__s3-lite-client";
import type { Config } from "config-manager";
import { MediaBackend, MediaBackendType, MediaHasher } from "..";
import type { ConvertableMediaFormats } from "../media-converter";
import { MediaConverter } from "../media-converter";
import { MediaBackend, MediaBackendType, MediaHasher } from "..";
import type { ConfigType } from "config-manager";
export class S3MediaBackend extends MediaBackend {
constructor(
config: ConfigType,
private s3Client = new S3Client({
endPoint: config.s3.endpoint,
useSSL: true,
region: config.s3.region || "auto",
bucket: config.s3.bucket_name,
accessKey: config.s3.access_key,
secretKey: config.s3.secret_access_key,
})
) {
super(config, MediaBackendType.S3);
}
constructor(
config: Config,
private s3Client = new S3Client({
endPoint: config.s3.endpoint,
useSSL: true,
region: config.s3.region || "auto",
bucket: config.s3.bucket_name,
accessKey: config.s3.access_key,
secretKey: config.s3.secret_access_key,
}),
) {
super(config, MediaBackendType.S3);
}
public async addFile(file: File) {
if (this.shouldConvertImages(this.config)) {
const fileExtension = file.name.split(".").pop();
const mediaConverter = new MediaConverter(
fileExtension as ConvertableMediaFormats,
this.config.media.conversion
.convert_to as ConvertableMediaFormats
);
file = await mediaConverter.convert(file);
}
public async addFile(file: File) {
let convertedFile = file;
if (this.shouldConvertImages(this.config)) {
const fileExtension = file.name.split(".").pop();
const mediaConverter = new MediaConverter(
fileExtension as ConvertableMediaFormats,
this.config.media.conversion
.convert_to as ConvertableMediaFormats,
);
convertedFile = await mediaConverter.convert(file);
}
const hash = await new MediaHasher().getMediaHash(file);
const hash = await new MediaHasher().getMediaHash(convertedFile);
await this.s3Client.putObject(file.name, file.stream(), {
size: file.size,
});
await this.s3Client.putObject(
convertedFile.name,
convertedFile.stream(),
{
size: convertedFile.size,
},
);
return {
uploadedFile: file,
hash: hash,
};
}
return {
uploadedFile: convertedFile,
hash: hash,
};
}
public async getFileByHash(
hash: string,
databaseHashFetcher: (sha256: string) => Promise<string | null>
): Promise<File | null> {
const filename = await databaseHashFetcher(hash);
public async getFileByHash(
hash: string,
databaseHashFetcher: (sha256: string) => Promise<string | null>,
): Promise<File | null> {
const filename = await databaseHashFetcher(hash);
if (!filename) return null;
if (!filename) return null;
return this.getFile(filename);
}
return this.getFile(filename);
}
public async getFile(filename: string): Promise<File | null> {
try {
await this.s3Client.statObject(filename);
} catch {
return null;
}
public async getFile(filename: string): Promise<File | null> {
try {
await this.s3Client.statObject(filename);
} catch {
return null;
}
const file = await this.s3Client.getObject(filename);
const file = await this.s3Client.getObject(filename);
return new File([await file.arrayBuffer()], filename, {
type: file.headers.get("Content-Type") || "undefined",
});
}
return new File([await file.arrayBuffer()], filename, {
type: file.headers.get("Content-Type") || "undefined",
});
}
}

View file

@ -1,101 +1,101 @@
import type { ConfigType } from "config-manager";
import type { Config } from "config-manager";
export enum MediaBackendType {
LOCAL = "local",
S3 = "s3",
LOCAL = "local",
S3 = "s3",
}
interface UploadedFileMetadata {
uploadedFile: File;
path?: string;
hash: string;
uploadedFile: File;
path?: string;
hash: string;
}
export class MediaHasher {
/**
* Returns the SHA-256 hash of a file in hex format
* @param media The file to hash
* @returns The SHA-256 hash of the file in hex format
*/
public async getMediaHash(media: File) {
const hash = new Bun.SHA256()
.update(await media.arrayBuffer())
.digest("hex");
/**
* Returns the SHA-256 hash of a file in hex format
* @param media The file to hash
* @returns The SHA-256 hash of the file in hex format
*/
public async getMediaHash(media: File) {
const hash = new Bun.SHA256()
.update(await media.arrayBuffer())
.digest("hex");
return hash;
}
return hash;
}
}
export class MediaBackend {
constructor(
public config: ConfigType,
public backend: MediaBackendType
) {}
constructor(
public config: Config,
public backend: MediaBackendType,
) {}
static async fromBackendType(
backend: MediaBackendType,
config: ConfigType
): Promise<MediaBackend> {
switch (backend) {
case MediaBackendType.LOCAL:
return new (await import("./backends/local")).LocalMediaBackend(
config
);
case MediaBackendType.S3:
return new (await import("./backends/s3")).S3MediaBackend(
config
);
default:
throw new Error(`Unknown backend type: ${backend as any}`);
}
}
static async fromBackendType(
backend: MediaBackendType,
config: Config,
): Promise<MediaBackend> {
switch (backend) {
case MediaBackendType.LOCAL:
return new (await import("./backends/local")).LocalMediaBackend(
config,
);
case MediaBackendType.S3:
return new (await import("./backends/s3")).S3MediaBackend(
config,
);
default:
throw new Error(`Unknown backend type: ${backend as string}`);
}
}
public getBackendType() {
return this.backend;
}
public getBackendType() {
return this.backend;
}
public shouldConvertImages(config: ConfigType) {
return config.media.conversion.convert_images;
}
public shouldConvertImages(config: Config) {
return config.media.conversion.convert_images;
}
/**
* Fetches file from backend from SHA-256 hash
* @param file SHA-256 hash of wanted file
* @param databaseHashFetcher Function that takes in a sha256 hash as input and outputs the filename of that file in the database
* @returns The file as a File object
*/
public getFileByHash(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
file: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
databaseHashFetcher: (sha256: string) => Promise<string>
): Promise<File | null> {
return Promise.reject(
new Error("Do not call MediaBackend directly: use a subclass")
);
}
/**
* Fetches file from backend from SHA-256 hash
* @param file SHA-256 hash of wanted file
* @param databaseHashFetcher Function that takes in a sha256 hash as input and outputs the filename of that file in the database
* @returns The file as a File object
*/
public getFileByHash(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
file: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
databaseHashFetcher: (sha256: string) => Promise<string>,
): Promise<File | null> {
return Promise.reject(
new Error("Do not call MediaBackend directly: use a subclass"),
);
}
/**
* Fetches file from backend from filename
* @param filename File name
* @returns The file as a File object
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public getFile(filename: string): Promise<File | null> {
return Promise.reject(
new Error("Do not call MediaBackend directly: use a subclass")
);
}
/**
* Fetches file from backend from filename
* @param filename File name
* @returns The file as a File object
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public getFile(filename: string): Promise<File | null> {
return Promise.reject(
new Error("Do not call MediaBackend directly: use a subclass"),
);
}
/**
* Adds file to backend
* @param file File to add
* @returns Metadata about the uploaded file
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public addFile(file: File): Promise<UploadedFileMetadata> {
return Promise.reject(
new Error("Do not call MediaBackend directly: use a subclass")
);
}
/**
* Adds file to backend
* @param file File to add
* @returns Metadata about the uploaded file
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public addFile(file: File): Promise<UploadedFileMetadata> {
return Promise.reject(
new Error("Do not call MediaBackend directly: use a subclass"),
);
}
}

View file

@ -6,89 +6,89 @@
import sharp from "sharp";
export enum ConvertableMediaFormats {
PNG = "png",
WEBP = "webp",
JPEG = "jpeg",
JPG = "jpg",
AVIF = "avif",
JXL = "jxl",
HEIF = "heif",
PNG = "png",
WEBP = "webp",
JPEG = "jpeg",
JPG = "jpg",
AVIF = "avif",
JXL = "jxl",
HEIF = "heif",
}
/**
* Handles media conversion between formats
*/
export class MediaConverter {
constructor(
public fromFormat: ConvertableMediaFormats,
public toFormat: ConvertableMediaFormats
) {}
constructor(
public fromFormat: ConvertableMediaFormats,
public toFormat: ConvertableMediaFormats,
) {}
/**
* Returns whether the media is convertable
* @returns Whether the media is convertable
*/
public isConvertable() {
return (
this.fromFormat !== this.toFormat &&
Object.values(ConvertableMediaFormats).includes(this.fromFormat)
);
}
/**
* Returns whether the media is convertable
* @returns Whether the media is convertable
*/
public isConvertable() {
return (
this.fromFormat !== this.toFormat &&
Object.values(ConvertableMediaFormats).includes(this.fromFormat)
);
}
/**
* Returns the file name with the extension replaced
* @param fileName File name to replace
* @returns File name with extension replaced
*/
private getReplacedFileName(fileName: string) {
return this.extractFilenameFromPath(fileName).replace(
new RegExp(`\\.${this.fromFormat}$`),
`.${this.toFormat}`
);
}
/**
* Returns the file name with the extension replaced
* @param fileName File name to replace
* @returns File name with extension replaced
*/
private getReplacedFileName(fileName: string) {
return this.extractFilenameFromPath(fileName).replace(
new RegExp(`\\.${this.fromFormat}$`),
`.${this.toFormat}`,
);
}
/**
* Extracts the filename from a path
* @param path Path to extract filename from
* @returns Extracted filename
*/
private extractFilenameFromPath(path: string) {
// Don't count escaped slashes as path separators
const pathParts = path.split(/(?<!\\)\//);
return pathParts[pathParts.length - 1];
}
/**
* Extracts the filename from a path
* @param path Path to extract filename from
* @returns Extracted filename
*/
private extractFilenameFromPath(path: string) {
// Don't count escaped slashes as path separators
const pathParts = path.split(/(?<!\\)\//);
return pathParts[pathParts.length - 1];
}
/**
* Converts media to the specified format
* @param media Media to convert
* @returns Converted media
*/
public async convert(media: File) {
if (!this.isConvertable()) {
return media;
}
/**
* Converts media to the specified format
* @param media Media to convert
* @returns Converted media
*/
public async convert(media: File) {
if (!this.isConvertable()) {
return media;
}
const sharpCommand = sharp(await media.arrayBuffer());
const sharpCommand = sharp(await media.arrayBuffer());
// Calculate newFilename before changing formats to prevent errors with jpg files
const newFilename = this.getReplacedFileName(media.name);
// Calculate newFilename before changing formats to prevent errors with jpg files
const newFilename = this.getReplacedFileName(media.name);
if (this.fromFormat === ConvertableMediaFormats.JPG) {
this.fromFormat = ConvertableMediaFormats.JPEG;
}
if (this.fromFormat === ConvertableMediaFormats.JPG) {
this.fromFormat = ConvertableMediaFormats.JPEG;
}
if (this.toFormat === ConvertableMediaFormats.JPG) {
this.toFormat = ConvertableMediaFormats.JPEG;
}
if (this.toFormat === ConvertableMediaFormats.JPG) {
this.toFormat = ConvertableMediaFormats.JPEG;
}
const convertedBuffer = await sharpCommand[this.toFormat]().toBuffer();
const convertedBuffer = await sharpCommand[this.toFormat]().toBuffer();
// Convert the buffer to a BlobPart
const buffer = new Blob([convertedBuffer]);
// Convert the buffer to a BlobPart
const buffer = new Blob([convertedBuffer]);
return new File([buffer], newFilename, {
type: `image/${this.toFormat}`,
lastModified: Date.now(),
});
}
return new File([buffer], newFilename, {
type: `image/${this.toFormat}`,
lastModified: Date.now(),
});
}
}

View file

@ -1,9 +1,9 @@
{
"name": "media-manager",
"version": "0.0.0",
"main": "index.ts",
"dependencies": {
"@jsr/bradenmacdonald__s3-lite-client": "npm:@jsr/bradenmacdonald__s3-lite-client",
"config-manager": "workspace:*"
}
"name": "media-manager",
"version": "0.0.0",
"main": "index.ts",
"dependencies": {
"@jsr/bradenmacdonald__s3-lite-client": "npm:@jsr/bradenmacdonald__s3-lite-client",
"config-manager": "workspace:*"
}
}

View file

@ -1,276 +1,277 @@
import { beforeEach, describe, expect, it, jest, spyOn } from "bun:test";
import type { S3Client } from "@jsr/bradenmacdonald__s3-lite-client";
import type { Config } from "config-manager";
// FILEPATH: /home/jessew/Dev/lysand/packages/media-manager/backends/s3.test.ts
import { MediaBackend, MediaBackendType, MediaHasher } from "..";
import type { S3Client } from "@bradenmacdonald/s3-lite-client";
import { beforeEach, describe, jest, it, expect, spyOn } from "bun:test";
import { S3MediaBackend } from "../backends/s3";
import type { ConfigType } from "config-manager";
import { ConvertableMediaFormats, MediaConverter } from "../media-converter";
import { LocalMediaBackend } from "../backends/local";
import { S3MediaBackend } from "../backends/s3";
import { ConvertableMediaFormats, MediaConverter } from "../media-converter";
type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
[P in keyof T]?: DeepPartial<T[P]>;
};
describe("MediaBackend", () => {
let mediaBackend: MediaBackend;
let mockConfig: ConfigType;
let mediaBackend: MediaBackend;
let mockConfig: Config;
beforeEach(() => {
mockConfig = {
media: {
conversion: {
convert_images: true,
},
},
} as ConfigType;
mediaBackend = new MediaBackend(mockConfig, MediaBackendType.S3);
});
beforeEach(() => {
mockConfig = {
media: {
conversion: {
convert_images: true,
},
},
} as Config;
mediaBackend = new MediaBackend(mockConfig, MediaBackendType.S3);
});
it("should initialize with correct backend type", () => {
expect(mediaBackend.getBackendType()).toEqual(MediaBackendType.S3);
});
it("should initialize with correct backend type", () => {
expect(mediaBackend.getBackendType()).toEqual(MediaBackendType.S3);
});
describe("fromBackendType", () => {
it("should return a LocalMediaBackend instance for LOCAL backend type", async () => {
const backend = await MediaBackend.fromBackendType(
MediaBackendType.LOCAL,
mockConfig
);
expect(backend).toBeInstanceOf(LocalMediaBackend);
});
describe("fromBackendType", () => {
it("should return a LocalMediaBackend instance for LOCAL backend type", async () => {
const backend = await MediaBackend.fromBackendType(
MediaBackendType.LOCAL,
mockConfig,
);
expect(backend).toBeInstanceOf(LocalMediaBackend);
});
it("should return a S3MediaBackend instance for S3 backend type", async () => {
const backend = await MediaBackend.fromBackendType(
MediaBackendType.S3,
{
s3: {
endpoint: "localhost:4566",
region: "us-east-1",
bucket_name: "test-bucket",
access_key: "test-access",
public_url: "test",
secret_access_key: "test-secret",
},
} as ConfigType
);
expect(backend).toBeInstanceOf(S3MediaBackend);
});
it("should return a S3MediaBackend instance for S3 backend type", async () => {
const backend = await MediaBackend.fromBackendType(
MediaBackendType.S3,
{
s3: {
endpoint: "localhost:4566",
region: "us-east-1",
bucket_name: "test-bucket",
access_key: "test-access",
public_url: "test",
secret_access_key: "test-secret",
},
} as Config,
);
expect(backend).toBeInstanceOf(S3MediaBackend);
});
it("should throw an error for unknown backend type", () => {
expect(
MediaBackend.fromBackendType("unknown" as any, mockConfig)
).rejects.toThrow("Unknown backend type: unknown");
});
});
it("should throw an error for unknown backend type", () => {
expect(
// @ts-expect-error This is a test
MediaBackend.fromBackendType("unknown", mockConfig),
).rejects.toThrow("Unknown backend type: unknown");
});
});
it("should check if images should be converted", () => {
expect(mediaBackend.shouldConvertImages(mockConfig)).toBe(true);
mockConfig.media.conversion.convert_images = false;
expect(mediaBackend.shouldConvertImages(mockConfig)).toBe(false);
});
it("should check if images should be converted", () => {
expect(mediaBackend.shouldConvertImages(mockConfig)).toBe(true);
mockConfig.media.conversion.convert_images = false;
expect(mediaBackend.shouldConvertImages(mockConfig)).toBe(false);
});
it("should throw error when calling getFileByHash", () => {
const mockHash = "test-hash";
const databaseHashFetcher = jest.fn().mockResolvedValue("test.jpg");
it("should throw error when calling getFileByHash", () => {
const mockHash = "test-hash";
const databaseHashFetcher = jest.fn().mockResolvedValue("test.jpg");
expect(
mediaBackend.getFileByHash(mockHash, databaseHashFetcher)
).rejects.toThrow(Error);
});
expect(
mediaBackend.getFileByHash(mockHash, databaseHashFetcher),
).rejects.toThrow(Error);
});
it("should throw error when calling getFile", () => {
const mockFilename = "test.jpg";
it("should throw error when calling getFile", () => {
const mockFilename = "test.jpg";
expect(mediaBackend.getFile(mockFilename)).rejects.toThrow(Error);
});
expect(mediaBackend.getFile(mockFilename)).rejects.toThrow(Error);
});
it("should throw error when calling addFile", () => {
const mockFile = new File([""], "test.jpg");
it("should throw error when calling addFile", () => {
const mockFile = new File([""], "test.jpg");
expect(mediaBackend.addFile(mockFile)).rejects.toThrow();
});
expect(mediaBackend.addFile(mockFile)).rejects.toThrow();
});
});
describe("S3MediaBackend", () => {
let s3MediaBackend: S3MediaBackend;
let mockS3Client: Partial<S3Client>;
let mockConfig: DeepPartial<ConfigType>;
let mockFile: File;
let mockMediaHasher: MediaHasher;
let s3MediaBackend: S3MediaBackend;
let mockS3Client: Partial<S3Client>;
let mockConfig: DeepPartial<Config>;
let mockFile: File;
let mockMediaHasher: MediaHasher;
beforeEach(() => {
mockConfig = {
s3: {
endpoint: "http://localhost:4566",
region: "us-east-1",
bucket_name: "test-bucket",
access_key: "test-access-key",
secret_access_key: "test-secret-access-key",
public_url: "test",
},
media: {
conversion: {
convert_to: ConvertableMediaFormats.PNG,
},
},
};
mockFile = new File([new TextEncoder().encode("test")], "test.jpg");
mockMediaHasher = new MediaHasher();
mockS3Client = {
putObject: jest.fn().mockResolvedValue({}),
statObject: jest.fn().mockResolvedValue({}),
getObject: jest.fn().mockResolvedValue({
blob: jest.fn().mockResolvedValue(new Blob()),
headers: new Headers({ "Content-Type": "image/jpeg" }),
}),
} as Partial<S3Client>;
s3MediaBackend = new S3MediaBackend(
mockConfig as ConfigType,
mockS3Client as S3Client
);
});
beforeEach(() => {
mockConfig = {
s3: {
endpoint: "http://localhost:4566",
region: "us-east-1",
bucket_name: "test-bucket",
access_key: "test-access-key",
secret_access_key: "test-secret-access-key",
public_url: "test",
},
media: {
conversion: {
convert_to: ConvertableMediaFormats.PNG,
},
},
};
mockFile = new File([new TextEncoder().encode("test")], "test.jpg");
mockMediaHasher = new MediaHasher();
mockS3Client = {
putObject: jest.fn().mockResolvedValue({}),
statObject: jest.fn().mockResolvedValue({}),
getObject: jest.fn().mockResolvedValue({
blob: jest.fn().mockResolvedValue(new Blob()),
headers: new Headers({ "Content-Type": "image/jpeg" }),
}),
} as Partial<S3Client>;
s3MediaBackend = new S3MediaBackend(
mockConfig as Config,
mockS3Client as S3Client,
);
});
it("should initialize with correct type", () => {
expect(s3MediaBackend.getBackendType()).toEqual(MediaBackendType.S3);
});
it("should initialize with correct type", () => {
expect(s3MediaBackend.getBackendType()).toEqual(MediaBackendType.S3);
});
it("should add file", async () => {
const mockHash = "test-hash";
spyOn(mockMediaHasher, "getMediaHash").mockResolvedValue(mockHash);
it("should add file", async () => {
const mockHash = "test-hash";
spyOn(mockMediaHasher, "getMediaHash").mockResolvedValue(mockHash);
const result = await s3MediaBackend.addFile(mockFile);
const result = await s3MediaBackend.addFile(mockFile);
expect(result.uploadedFile).toEqual(mockFile);
expect(result.hash).toHaveLength(64);
expect(mockS3Client.putObject).toHaveBeenCalledWith(
mockFile.name,
expect.any(ReadableStream),
{ size: mockFile.size }
);
});
expect(result.uploadedFile).toEqual(mockFile);
expect(result.hash).toHaveLength(64);
expect(mockS3Client.putObject).toHaveBeenCalledWith(
mockFile.name,
expect.any(ReadableStream),
{ size: mockFile.size },
);
});
it("should get file by hash", async () => {
const mockHash = "test-hash";
const mockFilename = "test.jpg";
const databaseHashFetcher = jest.fn().mockResolvedValue(mockFilename);
mockS3Client.statObject = jest.fn().mockResolvedValue({});
mockS3Client.getObject = jest.fn().mockResolvedValue({
arrayBuffer: jest.fn().mockResolvedValue(new ArrayBuffer(10)),
headers: new Headers({ "Content-Type": "image/jpeg" }),
});
it("should get file by hash", async () => {
const mockHash = "test-hash";
const mockFilename = "test.jpg";
const databaseHashFetcher = jest.fn().mockResolvedValue(mockFilename);
mockS3Client.statObject = jest.fn().mockResolvedValue({});
mockS3Client.getObject = jest.fn().mockResolvedValue({
arrayBuffer: jest.fn().mockResolvedValue(new ArrayBuffer(10)),
headers: new Headers({ "Content-Type": "image/jpeg" }),
});
const file = await s3MediaBackend.getFileByHash(
mockHash,
databaseHashFetcher
);
const file = await s3MediaBackend.getFileByHash(
mockHash,
databaseHashFetcher,
);
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
it("should get file", async () => {
const mockFilename = "test.jpg";
mockS3Client.statObject = jest.fn().mockResolvedValue({});
mockS3Client.getObject = jest.fn().mockResolvedValue({
arrayBuffer: jest.fn().mockResolvedValue(new ArrayBuffer(10)),
headers: new Headers({ "Content-Type": "image/jpeg" }),
});
it("should get file", async () => {
const mockFilename = "test.jpg";
mockS3Client.statObject = jest.fn().mockResolvedValue({});
mockS3Client.getObject = jest.fn().mockResolvedValue({
arrayBuffer: jest.fn().mockResolvedValue(new ArrayBuffer(10)),
headers: new Headers({ "Content-Type": "image/jpeg" }),
});
const file = await s3MediaBackend.getFile(mockFilename);
const file = await s3MediaBackend.getFile(mockFilename);
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
});
describe("LocalMediaBackend", () => {
let localMediaBackend: LocalMediaBackend;
let mockConfig: ConfigType;
let mockFile: File;
let mockMediaHasher: MediaHasher;
let localMediaBackend: LocalMediaBackend;
let mockConfig: Config;
let mockFile: File;
let mockMediaHasher: MediaHasher;
beforeEach(() => {
mockConfig = {
media: {
conversion: {
convert_images: true,
convert_to: ConvertableMediaFormats.PNG,
},
local_uploads_folder: "./uploads",
},
} as ConfigType;
mockFile = Bun.file(__dirname + "/megamind.jpg") as unknown as File;
mockMediaHasher = new MediaHasher();
localMediaBackend = new LocalMediaBackend(mockConfig);
});
beforeEach(() => {
mockConfig = {
media: {
conversion: {
convert_images: true,
convert_to: ConvertableMediaFormats.PNG,
},
local_uploads_folder: "./uploads",
},
} as Config;
mockFile = Bun.file(`${__dirname}/megamind.jpg`) as unknown as File;
mockMediaHasher = new MediaHasher();
localMediaBackend = new LocalMediaBackend(mockConfig);
});
it("should initialize with correct type", () => {
expect(localMediaBackend.getBackendType()).toEqual(
MediaBackendType.LOCAL
);
});
it("should initialize with correct type", () => {
expect(localMediaBackend.getBackendType()).toEqual(
MediaBackendType.LOCAL,
);
});
it("should add file", async () => {
const mockHash = "test-hash";
spyOn(mockMediaHasher, "getMediaHash").mockResolvedValue(mockHash);
const mockMediaConverter = new MediaConverter(
ConvertableMediaFormats.JPG,
ConvertableMediaFormats.PNG
);
spyOn(mockMediaConverter, "convert").mockResolvedValue(mockFile);
// @ts-expect-error This is a mock
spyOn(Bun, "file").mockImplementationOnce(() => ({
exists: () => Promise.resolve(false),
}));
spyOn(Bun, "write").mockImplementationOnce(() =>
Promise.resolve(mockFile.size)
);
it("should add file", async () => {
const mockHash = "test-hash";
spyOn(mockMediaHasher, "getMediaHash").mockResolvedValue(mockHash);
const mockMediaConverter = new MediaConverter(
ConvertableMediaFormats.JPG,
ConvertableMediaFormats.PNG,
);
spyOn(mockMediaConverter, "convert").mockResolvedValue(mockFile);
// @ts-expect-error This is a mock
spyOn(Bun, "file").mockImplementationOnce(() => ({
exists: () => Promise.resolve(false),
}));
spyOn(Bun, "write").mockImplementationOnce(() =>
Promise.resolve(mockFile.size),
);
const result = await localMediaBackend.addFile(mockFile);
const result = await localMediaBackend.addFile(mockFile);
expect(result.uploadedFile).toEqual(mockFile);
expect(result.path).toEqual(`./uploads/megamind.png`);
expect(result.hash).toHaveLength(64);
});
expect(result.uploadedFile).toEqual(mockFile);
expect(result.path).toEqual("./uploads/megamind.png");
expect(result.hash).toHaveLength(64);
});
it("should get file by hash", async () => {
const mockHash = "test-hash";
const mockFilename = "test.jpg";
const databaseHashFetcher = jest.fn().mockResolvedValue(mockFilename);
// @ts-expect-error This is a mock
spyOn(Bun, "file").mockImplementationOnce(() => ({
exists: () => Promise.resolve(true),
arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
type: "image/jpeg",
lastModified: 123456789,
}));
it("should get file by hash", async () => {
const mockHash = "test-hash";
const mockFilename = "test.jpg";
const databaseHashFetcher = jest.fn().mockResolvedValue(mockFilename);
// @ts-expect-error This is a mock
spyOn(Bun, "file").mockImplementationOnce(() => ({
exists: () => Promise.resolve(true),
arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
type: "image/jpeg",
lastModified: 123456789,
}));
const file = await localMediaBackend.getFileByHash(
mockHash,
databaseHashFetcher
);
const file = await localMediaBackend.getFileByHash(
mockHash,
databaseHashFetcher,
);
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
it("should get file", async () => {
const mockFilename = "test.jpg";
// @ts-expect-error This is a mock
spyOn(Bun, "file").mockImplementationOnce(() => ({
exists: () => Promise.resolve(true),
arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
type: "image/jpeg",
lastModified: 123456789,
}));
it("should get file", async () => {
const mockFilename = "test.jpg";
// @ts-expect-error This is a mock
spyOn(Bun, "file").mockImplementationOnce(() => ({
exists: () => Promise.resolve(true),
arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
type: "image/jpeg",
lastModified: 123456789,
}));
const file = await localMediaBackend.getFile(mockFilename);
const file = await localMediaBackend.getFile(mockFilename);
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
expect(file).not.toBeNull();
expect(file?.name).toEqual(mockFilename);
expect(file?.type).toEqual("image/jpeg");
});
});

View file

@ -1,65 +1,65 @@
// FILEPATH: /home/jessew/Dev/lysand/packages/media-manager/media-converter.test.ts
import { describe, it, expect, beforeEach } from "bun:test";
import { MediaConverter, ConvertableMediaFormats } from "../media-converter";
import { beforeEach, describe, expect, it } from "bun:test";
import { ConvertableMediaFormats, MediaConverter } from "../media-converter";
describe("MediaConverter", () => {
let mediaConverter: MediaConverter;
let mediaConverter: MediaConverter;
beforeEach(() => {
mediaConverter = new MediaConverter(
ConvertableMediaFormats.JPG,
ConvertableMediaFormats.PNG
);
});
beforeEach(() => {
mediaConverter = new MediaConverter(
ConvertableMediaFormats.JPG,
ConvertableMediaFormats.PNG,
);
});
it("should initialize with correct formats", () => {
expect(mediaConverter.fromFormat).toEqual(ConvertableMediaFormats.JPG);
expect(mediaConverter.toFormat).toEqual(ConvertableMediaFormats.PNG);
});
it("should initialize with correct formats", () => {
expect(mediaConverter.fromFormat).toEqual(ConvertableMediaFormats.JPG);
expect(mediaConverter.toFormat).toEqual(ConvertableMediaFormats.PNG);
});
it("should check if media is convertable", () => {
expect(mediaConverter.isConvertable()).toBe(true);
mediaConverter.toFormat = ConvertableMediaFormats.JPG;
expect(mediaConverter.isConvertable()).toBe(false);
});
it("should check if media is convertable", () => {
expect(mediaConverter.isConvertable()).toBe(true);
mediaConverter.toFormat = ConvertableMediaFormats.JPG;
expect(mediaConverter.isConvertable()).toBe(false);
});
it("should replace file name extension", () => {
const fileName = "test.jpg";
const expectedFileName = "test.png";
// Written like this because it's a private function
expect(mediaConverter["getReplacedFileName"](fileName)).toEqual(
expectedFileName
);
});
it("should replace file name extension", () => {
const fileName = "test.jpg";
const expectedFileName = "test.png";
// Written like this because it's a private function
expect(mediaConverter.getReplacedFileName(fileName)).toEqual(
expectedFileName,
);
});
describe("Filename extractor", () => {
it("should extract filename from path", () => {
const path = "path/to/test.jpg";
const expectedFileName = "test.jpg";
expect(mediaConverter["extractFilenameFromPath"](path)).toEqual(
expectedFileName
);
});
describe("Filename extractor", () => {
it("should extract filename from path", () => {
const path = "path/to/test.jpg";
const expectedFileName = "test.jpg";
expect(mediaConverter.extractFilenameFromPath(path)).toEqual(
expectedFileName,
);
});
it("should handle escaped slashes", () => {
const path = "path/to/test\\/test.jpg";
const expectedFileName = "test\\/test.jpg";
expect(mediaConverter["extractFilenameFromPath"](path)).toEqual(
expectedFileName
);
});
});
it("should handle escaped slashes", () => {
const path = "path/to/test\\/test.jpg";
const expectedFileName = "test\\/test.jpg";
expect(mediaConverter.extractFilenameFromPath(path)).toEqual(
expectedFileName,
);
});
});
it("should convert media", async () => {
const file = Bun.file(__dirname + "/megamind.jpg");
it("should convert media", async () => {
const file = Bun.file(`${__dirname}/megamind.jpg`);
const convertedFile = await mediaConverter.convert(
file as unknown as File
);
const convertedFile = await mediaConverter.convert(
file as unknown as File,
);
expect(convertedFile.name).toEqual("megamind.png");
expect(convertedFile.type).toEqual(
`image/${ConvertableMediaFormats.PNG}`
);
});
expect(convertedFile.name).toEqual("megamind.png");
expect(convertedFile.type).toEqual(
`image/${ConvertableMediaFormats.PNG}`,
);
});
});

View file

@ -2,7 +2,7 @@ import type { APActor, APNote } from "activitypub-types";
import { ActivityPubTranslator } from "./protocols/activitypub";
export enum SupportedProtocols {
ACTIVITYPUB = "activitypub",
ACTIVITYPUB = "activitypub",
}
/**
@ -12,37 +12,40 @@ export enum SupportedProtocols {
* This class is not meant to be instantiated directly, but rather for its children to be used.
*/
export class ProtocolTranslator {
static auto(object: any) {
const protocol = this.recognizeProtocol(object);
switch (protocol) {
case SupportedProtocols.ACTIVITYPUB:
return new ActivityPubTranslator();
default:
throw new Error("Unknown protocol");
}
}
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
static auto(object: any) {
const protocol = ProtocolTranslator.recognizeProtocol(object);
switch (protocol) {
case SupportedProtocols.ACTIVITYPUB:
return new ActivityPubTranslator();
default:
throw new Error("Unknown protocol");
}
}
/**
* Translates an ActivityPub actor to a Lysand user
* @param data Raw JSON-LD data from an ActivityPub actor
*/
user(data: APActor) {
//
}
/**
* Translates an ActivityPub actor to a Lysand user
* @param data Raw JSON-LD data from an ActivityPub actor
*/
user(data: APActor) {
//
}
/**
* Translates an ActivityPub note to a Lysand status
* @param data Raw JSON-LD data from an ActivityPub note
*/
status(data: APNote) {
//
}
/**
* Translates an ActivityPub note to a Lysand status
* @param data Raw JSON-LD data from an ActivityPub note
*/
status(data: APNote) {
//
}
/**
* Automatically recognizes the protocol of a given object
*/
private static recognizeProtocol(object: any) {
// Temporary stub
return SupportedProtocols.ACTIVITYPUB;
}
/**
* Automatically recognizes the protocol of a given object
*/
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
private static recognizeProtocol(object: any) {
// Temporary stub
return SupportedProtocols.ACTIVITYPUB;
}
}

View file

@ -1,9 +1,9 @@
{
"name": "protocol-translator",
"version": "0.0.0",
"main": "index.ts",
"dependencies": {},
"devDependencies": {
"activitypub-types": "^1.1.0"
}
"name": "protocol-translator",
"version": "0.0.0",
"main": "index.ts",
"dependencies": {},
"devDependencies": {
"activitypub-types": "^1.1.0"
}
}

View file

@ -1,11 +1,5 @@
import { ProtocolTranslator } from "..";
export class ActivityPubTranslator extends ProtocolTranslator {
constructor() {
super();
}
user() {
}
user() {}
}

View file

@ -13,158 +13,158 @@
* @returns JavaScript object of type T
*/
export class RequestParser {
constructor(public request: Request) {}
constructor(public request: Request) {}
/**
* Parse request body into a JavaScript object
* @returns JavaScript object of type T
* @throws Error if body is invalid
*/
async toObject<T>() {
try {
switch (await this.determineContentType()) {
case "application/json":
return this.parseJson<T>();
case "application/x-www-form-urlencoded":
return this.parseFormUrlencoded<T>();
case "multipart/form-data":
return this.parseFormData<T>();
default:
return this.parseQuery<T>();
}
} catch {
return {} as T;
}
}
/**
* Parse request body into a JavaScript object
* @returns JavaScript object of type T
* @throws Error if body is invalid
*/
async toObject<T>() {
try {
switch (await this.determineContentType()) {
case "application/json":
return this.parseJson<T>();
case "application/x-www-form-urlencoded":
return this.parseFormUrlencoded<T>();
case "multipart/form-data":
return this.parseFormData<T>();
default:
return this.parseQuery<T>();
}
} catch {
return {} as T;
}
}
/**
* Determine body content type
* If there is no Content-Type header, automatically
* guess content type. Cuts off after ";" character
* @returns Content-Type header value, or empty string if there is no body
* @throws Error if body is invalid
* @private
*/
private async determineContentType() {
if (this.request.headers.get("Content-Type")) {
return (
this.request.headers.get("Content-Type")?.split(";")[0] ?? ""
);
}
/**
* Determine body content type
* If there is no Content-Type header, automatically
* guess content type. Cuts off after ";" character
* @returns Content-Type header value, or empty string if there is no body
* @throws Error if body is invalid
* @private
*/
private async determineContentType() {
if (this.request.headers.get("Content-Type")) {
return (
this.request.headers.get("Content-Type")?.split(";")[0] ?? ""
);
}
// Check if body is valid JSON
try {
await this.request.json();
return "application/json";
} catch {
// This is not JSON
}
// Check if body is valid JSON
try {
await this.request.json();
return "application/json";
} catch {
// This is not JSON
}
// Check if body is valid FormData
try {
await this.request.formData();
return "multipart/form-data";
} catch {
// This is not FormData
}
// Check if body is valid FormData
try {
await this.request.formData();
return "multipart/form-data";
} catch {
// This is not FormData
}
if (this.request.body) {
throw new Error("Invalid body");
}
if (this.request.body) {
throw new Error("Invalid body");
}
// If there is no body, return query parameters
return "";
}
// If there is no body, return query parameters
return "";
}
/**
* Parse FormData body into a JavaScript object
* @returns JavaScript object of type T
* @private
* @throws Error if body is invalid
*/
private async parseFormData<T>(): Promise<Partial<T>> {
const formData = await this.request.formData();
const result: Partial<T> = {};
/**
* Parse FormData body into a JavaScript object
* @returns JavaScript object of type T
* @private
* @throws Error if body is invalid
*/
private async parseFormData<T>(): Promise<Partial<T>> {
const formData = await this.request.formData();
const result: Partial<T> = {};
for (const [key, value] of formData.entries()) {
if (value instanceof File) {
result[key as keyof T] = value as any;
} else if (key.endsWith("[]")) {
const arrayKey = key.slice(0, -2) as keyof T;
if (!result[arrayKey]) {
result[arrayKey] = [] as T[keyof T];
}
for (const [key, value] of formData.entries()) {
if (value instanceof File) {
result[key as keyof T] = value as T[keyof T];
} else if (key.endsWith("[]")) {
const arrayKey = key.slice(0, -2) as keyof T;
if (!result[arrayKey]) {
result[arrayKey] = [] as T[keyof T];
}
(result[arrayKey] as any[]).push(value);
} else {
result[key as keyof T] = value as any;
}
}
(result[arrayKey] as FormDataEntryValue[]).push(value);
} else {
result[key as keyof T] = value as T[keyof T];
}
}
return result;
}
return result;
}
/**
* Parse application/x-www-form-urlencoded body into a JavaScript object
* @returns JavaScript object of type T
* @private
* @throws Error if body is invalid
*/
private async parseFormUrlencoded<T>(): Promise<Partial<T>> {
const formData = await this.request.formData();
const result: Partial<T> = {};
/**
* Parse application/x-www-form-urlencoded body into a JavaScript object
* @returns JavaScript object of type T
* @private
* @throws Error if body is invalid
*/
private async parseFormUrlencoded<T>(): Promise<Partial<T>> {
const formData = await this.request.formData();
const result: Partial<T> = {};
for (const [key, value] of formData.entries()) {
if (key.endsWith("[]")) {
const arrayKey = key.slice(0, -2) as keyof T;
if (!result[arrayKey]) {
result[arrayKey] = [] as T[keyof T];
}
for (const [key, value] of formData.entries()) {
if (key.endsWith("[]")) {
const arrayKey = key.slice(0, -2) as keyof T;
if (!result[arrayKey]) {
result[arrayKey] = [] as T[keyof T];
}
(result[arrayKey] as any[]).push(value);
} else {
result[key as keyof T] = value as any;
}
}
(result[arrayKey] as FormDataEntryValue[]).push(value);
} else {
result[key as keyof T] = value as T[keyof T];
}
}
return result;
}
return result;
}
/**
* Parse JSON body into a JavaScript object
* @returns JavaScript object of type T
* @private
* @throws Error if body is invalid
*/
private async parseJson<T>(): Promise<Partial<T>> {
try {
return (await this.request.json()) as T;
} catch {
return {};
}
}
/**
* Parse JSON body into a JavaScript object
* @returns JavaScript object of type T
* @private
* @throws Error if body is invalid
*/
private async parseJson<T>(): Promise<Partial<T>> {
try {
return (await this.request.json()) as T;
} catch {
return {};
}
}
/**
* Parse query parameters into a JavaScript object
* @private
* @throws Error if body is invalid
* @returns JavaScript object of type T
*/
private parseQuery<T>(): Partial<T> {
const result: Partial<T> = {};
const url = new URL(this.request.url);
/**
* Parse query parameters into a JavaScript object
* @private
* @throws Error if body is invalid
* @returns JavaScript object of type T
*/
private parseQuery<T>(): Partial<T> {
const result: Partial<T> = {};
const url = new URL(this.request.url);
for (const [key, value] of url.searchParams.entries()) {
if (key.endsWith("[]")) {
const arrayKey = key.slice(0, -2) as keyof T;
if (!result[arrayKey]) {
result[arrayKey] = [] as T[keyof T];
}
(result[arrayKey] as string[]).push(value);
} else {
result[key as keyof T] = value as any;
}
}
return result;
}
for (const [key, value] of url.searchParams.entries()) {
if (key.endsWith("[]")) {
const arrayKey = key.slice(0, -2) as keyof T;
if (!result[arrayKey]) {
result[arrayKey] = [] as T[keyof T];
}
(result[arrayKey] as string[]).push(value);
} else {
result[key as keyof T] = value as T[keyof T];
}
}
return result;
}
}

View file

@ -1,158 +1,158 @@
import { describe, it, expect, test } from "bun:test";
import { describe, expect, it, test } from "bun:test";
import { RequestParser } from "..";
describe("RequestParser", () => {
describe("Should parse query parameters correctly", () => {
test("With text parameters", async () => {
const request = new Request(
"http://localhost?param1=value1&param2=value2"
);
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
describe("Should parse query parameters correctly", () => {
test("With text parameters", async () => {
const request = new Request(
"http://localhost?param1=value1&param2=value2",
);
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
test("With Array", async () => {
const request = new Request(
"http://localhost?test[]=value1&test[]=value2"
);
const result = await new RequestParser(request).toObject<{
test: string[];
}>();
expect(result.test).toEqual(["value1", "value2"]);
});
test("With Array", async () => {
const request = new Request(
"http://localhost?test[]=value1&test[]=value2",
);
const result = await new RequestParser(request).toObject<{
test: string[];
}>();
expect(result.test).toEqual(["value1", "value2"]);
});
test("With both at once", async () => {
const request = new Request(
"http://localhost?param1=value1&param2=value2&test[]=value1&test[]=value2"
);
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
test: string[];
}>();
expect(result).toEqual({
param1: "value1",
param2: "value2",
test: ["value1", "value2"],
});
});
});
test("With both at once", async () => {
const request = new Request(
"http://localhost?param1=value1&param2=value2&test[]=value1&test[]=value2",
);
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
test: string[];
}>();
expect(result).toEqual({
param1: "value1",
param2: "value2",
test: ["value1", "value2"],
});
});
});
it("should parse JSON body correctly", async () => {
const request = new Request("http://localhost", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ param1: "value1", param2: "value2" }),
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
it("should parse JSON body correctly", async () => {
const request = new Request("http://localhost", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ param1: "value1", param2: "value2" }),
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
it("should handle invalid JSON body", async () => {
const request = new Request("http://localhost", {
headers: { "Content-Type": "application/json" },
body: "invalid json",
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({});
});
it("should handle invalid JSON body", async () => {
const request = new Request("http://localhost", {
headers: { "Content-Type": "application/json" },
body: "invalid json",
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({});
});
describe("should parse form data correctly", () => {
test("With basic text parameters", async () => {
const formData = new FormData();
formData.append("param1", "value1");
formData.append("param2", "value2");
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
describe("should parse form data correctly", () => {
test("With basic text parameters", async () => {
const formData = new FormData();
formData.append("param1", "value1");
formData.append("param2", "value2");
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
test("With File object", async () => {
const file = new File(["content"], "filename.txt", {
type: "text/plain",
});
const formData = new FormData();
formData.append("file", file);
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
file: File;
}>();
expect(result.file).toBeInstanceOf(File);
expect(await result.file?.text()).toEqual("content");
});
test("With File object", async () => {
const file = new File(["content"], "filename.txt", {
type: "text/plain",
});
const formData = new FormData();
formData.append("file", file);
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
file: File;
}>();
expect(result.file).toBeInstanceOf(File);
expect(await result.file?.text()).toEqual("content");
});
test("With Array", async () => {
const formData = new FormData();
formData.append("test[]", "value1");
formData.append("test[]", "value2");
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
test: string[];
}>();
expect(result.test).toEqual(["value1", "value2"]);
});
test("With Array", async () => {
const formData = new FormData();
formData.append("test[]", "value1");
formData.append("test[]", "value2");
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
test: string[];
}>();
expect(result.test).toEqual(["value1", "value2"]);
});
test("With all three at once", async () => {
const file = new File(["content"], "filename.txt", {
type: "text/plain",
});
const formData = new FormData();
formData.append("param1", "value1");
formData.append("param2", "value2");
formData.append("file", file);
formData.append("test[]", "value1");
formData.append("test[]", "value2");
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
file: File;
test: string[];
}>();
expect(result).toEqual({
param1: "value1",
param2: "value2",
file: file,
test: ["value1", "value2"],
});
});
test("With all three at once", async () => {
const file = new File(["content"], "filename.txt", {
type: "text/plain",
});
const formData = new FormData();
formData.append("param1", "value1");
formData.append("param2", "value2");
formData.append("file", file);
formData.append("test[]", "value1");
formData.append("test[]", "value2");
const request = new Request("http://localhost", {
method: "POST",
body: formData,
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
file: File;
test: string[];
}>();
expect(result).toEqual({
param1: "value1",
param2: "value2",
file: file,
test: ["value1", "value2"],
});
});
test("URL Encoded", async () => {
const request = new Request("http://localhost", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "param1=value1&param2=value2",
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
});
test("URL Encoded", async () => {
const request = new Request("http://localhost", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "param1=value1&param2=value2",
});
const result = await new RequestParser(request).toObject<{
param1: string;
param2: string;
}>();
expect(result).toEqual({ param1: "value1", param2: "value2" });
});
});
});

View file

@ -1,6 +1,6 @@
<script setup>
// Import Tailwind style reset
import '@unocss/reset/tailwind-compat.css'
import "@unocss/reset/tailwind-compat.css";
</script>
<template>

View file

@ -10,7 +10,7 @@
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { ref } from "vue";
const props = defineProps<{
label: string;
@ -26,5 +26,5 @@ const checkValid = (e: Event) => {
} else {
isInvalid.value = true;
}
}
};
</script>

View file

@ -1,13 +1,13 @@
import { createApp } from "vue";
import "./style.css";
import "virtual:uno.css";
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import routes from "./routes";
import "./style.css";
const router = createRouter({
history: createWebHistory(),
routes: routes,
history: createWebHistory(),
routes: routes,
});
const app = createApp(App);

View file

@ -37,7 +37,7 @@
</template>
<script setup>
import { ref } from 'vue';
import { ref } from "vue";
const location = window.location;
const version = __VERSION__;

View file

@ -52,9 +52,9 @@
</template>
<script setup lang="ts">
import { useRoute } from 'vue-router';
import LoginInput from "../../components/LoginInput.vue"
import { onMounted, ref } from 'vue';
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import LoginInput from "../../components/LoginInput.vue";
const query = useRoute().query;
@ -64,18 +64,21 @@ const client_id = query.client_id;
const scope = query.scope;
const error = decodeURIComponent(query.error as string);
const oauthProviders = ref<{
name: string;
icon: string;
id: string
}[] | null>(null);
const oauthProviders = ref<
| {
name: string;
icon: string;
id: string;
}[]
| null
>(null);
const getOauthProviders = async () => {
const response = await fetch('/oauth/providers');
return await response.json() as any;
}
const response = await fetch("/oauth/providers");
return await response.json();
};
onMounted(async () => {
oauthProviders.value = await getOauthProviders();
})
oauthProviders.value = await getOauthProviders();
});
</script>

View file

@ -53,7 +53,7 @@
</template>
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { useRoute } from "vue-router";
const query = useRoute().query;
@ -61,7 +61,7 @@ const application = query.application;
const website = decodeURIComponent(query.website as string);
const redirect_uri = query.redirect_uri as string;
const client_id = query.client_id;
const scope = decodeURIComponent(query.scope as string || "");
const scope = decodeURIComponent((query.scope as string) || "");
const code = query.code;
const oauthScopeText: Record<string, string> = {
@ -79,7 +79,7 @@ const oauthScopeText: Record<string, string> = {
"w:conversations": "Edit your conversations",
"w:media": "Upload media",
"w:reports": "Report users",
}
};
const scopes = scope.split(" ");
@ -89,30 +89,56 @@ const scopes = scope.split(" ");
// Return an array of strings to display
// "read write:accounts" returns all the fields with $VERB as read, plus the accounts field with $VERB as write
const getScopeText = (fullScopes: string[]) => {
let scopeTexts = [];
const scopeTexts = [];
const readScopes = fullScopes.filter(scope => scope.includes("read"));
const writeScopes = fullScopes.filter(scope => scope.includes("write"));
const readScopes = fullScopes.filter((scope) => scope.includes("read"));
const writeScopes = fullScopes.filter((scope) => scope.includes("write"));
for (const possibleScope of Object.keys(oauthScopeText)) {
const [scopeAction, scopeName] = possibleScope.split(':');
const [scopeAction, scopeName] = possibleScope.split(":");
if (scopeAction.includes("rw") && (readScopes.includes(`read:${scopeName}`) || readScopes.find(scope => scope === "read")) && (writeScopes.includes(`write:${scopeName}`) || writeScopes.find(scope => scope === "write"))) {
if (oauthScopeText[possibleScope].includes("$VERB")) scopeTexts.push(["Read and write", oauthScopeText[possibleScope].replace("$VERB", "")]);
if (
scopeAction.includes("rw") &&
(readScopes.includes(`read:${scopeName}`) ||
readScopes.find((scope) => scope === "read")) &&
(writeScopes.includes(`write:${scopeName}`) ||
writeScopes.find((scope) => scope === "write"))
) {
if (oauthScopeText[possibleScope].includes("$VERB"))
scopeTexts.push([
"Read and write",
oauthScopeText[possibleScope].replace("$VERB", ""),
]);
else scopeTexts.push(["", oauthScopeText[possibleScope]]);
continue;
}
if (scopeAction.includes('r') && (readScopes.includes(`read:${scopeName}`) || readScopes.find(scope => scope === "read"))) {
if (oauthScopeText[possibleScope].includes("$VERB")) scopeTexts.push(["Read", oauthScopeText[possibleScope].replace("$VERB", "")]);
if (
scopeAction.includes("r") &&
(readScopes.includes(`read:${scopeName}`) ||
readScopes.find((scope) => scope === "read"))
) {
if (oauthScopeText[possibleScope].includes("$VERB"))
scopeTexts.push([
"Read",
oauthScopeText[possibleScope].replace("$VERB", ""),
]);
else scopeTexts.push(["", oauthScopeText[possibleScope]]);
}
if (scopeAction.includes('w') && (writeScopes.includes(`write:${scopeName}`) || writeScopes.find(scope => scope === "write"))) {
if (oauthScopeText[possibleScope].includes("$VERB")) scopeTexts.push(["Write", oauthScopeText[possibleScope].replace("$VERB", "")]);
if (
scopeAction.includes("w") &&
(writeScopes.includes(`write:${scopeName}`) ||
writeScopes.find((scope) => scope === "write"))
) {
if (oauthScopeText[possibleScope].includes("$VERB"))
scopeTexts.push([
"Write",
oauthScopeText[possibleScope].replace("$VERB", ""),
]);
else scopeTexts.push(["", oauthScopeText[possibleScope]]);
}
}
return scopeTexts;
}
};
</script>

View file

@ -98,12 +98,14 @@
</template>
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import type { APIInstance } from "~types/entities/instance";
import LoginInput from "../../components/LoginInput.vue"
import { computed, ref, watch } from 'vue';
import LoginInput from "../../components/LoginInput.vue";
const instanceInfo = await fetch("/api/v1/instance").then(res => res.json()) as APIInstance & {
tos_url: string
const instanceInfo = (await fetch("/api/v1/instance").then((res) =>
res.json(),
)) as APIInstance & {
tos_url: string;
};
const errors = ref<{
@ -124,26 +126,40 @@ const registerUser = (e: Event) => {
e.preventDefault();
const formData = new FormData();
formData.append("email", (e.target as any).email.value);
formData.append("password", (e.target as any).password.value);
formData.append("username", (e.target as any).username.value);
const target = e.target as unknown as Record<string, HTMLInputElement>;
formData.append("email", target.email.value);
formData.append("password", target.password.value);
formData.append("username", target.username.value);
formData.append("reason", reason.value);
formData.append("locale", "en")
formData.append("locale", "en");
formData.append("agreement", "true");
// @ts-ignore
fetch("/api/v1/accounts", {
method: "POST",
body: formData,
}).then(async res => {
if (res.status === 422) {
errors.value = (await res.json() as any).details;
console.log(errors.value)
} else {
// @ts-ignore
window.location.href = "/register/success";
}
}).catch(async err => {
console.error(err);
})
}
.then(async (res) => {
if (res.status === 422) {
errors.value = (
(await res.json()) as Record<
string,
{
[key: string]: {
error: string;
description: string;
}[];
}
>
).details;
console.log(errors.value);
} else {
// @ts-ignore
window.location.href = "/register/success";
}
})
.catch(async (err) => {
console.error(err);
});
};
</script>

View file

@ -6,9 +6,9 @@ import registerIndexVue from "./pages/register/index.vue";
import successVue from "./pages/register/success.vue";
export default [
{ path: "/", component: indexVue },
{ path: "/oauth/authorize", component: authorizeVue },
{ path: "/oauth/redirect", component: redirectVue },
{ path: "/register", component: registerIndexVue },
{ path: "/register/success", component: successVue },
{ path: "/", component: indexVue },
{ path: "/oauth/authorize", component: authorizeVue },
{ path: "/oauth/redirect", component: redirectVue },
{ path: "/register", component: registerIndexVue },
{ path: "/register/success", component: successVue },
] as RouteRecordRaw[];

View file

@ -1,35 +1,35 @@
import { defineConfig } from "vite";
import UnoCSS from "unocss/vite";
import vue from "@vitejs/plugin-vue";
import UnoCSS from "unocss/vite";
import { defineConfig } from "vite";
import pkg from "../package.json";
export default defineConfig({
base: "/",
build: {
outDir: "./dist",
},
// main.ts is in pages/ directory
resolve: {
alias: {
vue: "vue/dist/vue.esm-bundler",
},
},
server: {
hmr: {
clientPort: 5173,
},
},
define: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
__VERSION__: JSON.stringify(pkg.version),
},
ssr: {
noExternal: ["@prisma/client"],
},
plugins: [
UnoCSS({
mode: "global",
}),
vue(),
],
base: "/",
build: {
outDir: "./dist",
},
// main.ts is in pages/ directory
resolve: {
alias: {
vue: "vue/dist/vue.esm-bundler",
},
},
server: {
hmr: {
clientPort: 5173,
},
},
define: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
__VERSION__: JSON.stringify(pkg.version),
},
ssr: {
noExternal: ["@prisma/client"],
},
plugins: [
UnoCSS({
mode: "global",
}),
vue(),
],
});

View file

@ -2,11 +2,11 @@ import type { Server } from "./types";
import { HookTypes } from "./types";
const registerPlugin = (server: Server) => {
server.on(HookTypes.OnPostCreate, (req, newPost, author) => {
console.log("New post created!");
console.log(`Post details: ${newPost.content} (${newPost.id})`);
console.log(`Made by ${author.username} (${author.id})`);
});
server.on(HookTypes.OnPostCreate, (req, newPost, author) => {
console.log("New post created!");
console.log(`Post details: ${newPost.content} (${newPost.id})`);
console.log(`Made by ${author.username} (${author.id})`);
});
};
export default registerPlugin;

View file

@ -4,152 +4,152 @@ import type { UserWithRelations } from "~database/entities/User";
import type { LysandObjectType } from "~types/lysand/Object";
export enum HookTypes {
/**
* Called before the server starts listening
*/
PreServe = "preServe",
/**
* Called after the server stops listening
*/
PostServe = "postServe",
/**
* Called on every HTTP request (before anything else is done)
*/
OnRequestReceive = "onRequestReceive",
/**
* Called on every HTTP request (after it is processed)
*/
OnRequestProcessed = "onRequestProcessed",
/**
* Called on every object received (before it is parsed and added to the database)
*/
OnObjectReceive = "onObjectReceive",
/**
* Called on every object processed (after it is parsed and added to the database)
*/
OnObjectProcessed = "onObjectProcessed",
/**
* Called when signature verification fails on an object
*/
OnCryptoFail = "onCryptoFail",
/**
* Called when signature verification succeeds on an object
*/
OnCryptoSuccess = "onCryptoSuccess",
/**
* Called when a user is banned by another user
*/
OnBan = "onBan",
/**
* Called when a user is suspended by another user
*/
OnSuspend = "onSuspend",
/**
* Called when a user is blocked by another user
*/
OnUserBlock = "onUserBlock",
/**
* Called when a user is muted by another user
*/
OnUserMute = "onUserMute",
/**
* Called when a user is followed by another user
*/
OnUserFollow = "onUserFollow",
/**
* Called when a user registers (before completing email verification)
*/
OnRegister = "onRegister",
/**
* Called when a user finishes registering (after completing email verification)
*/
OnRegisterFinish = "onRegisterFinish",
/**
* Called when a user deletes their account
*/
OnDeleteAccount = "onDeleteAccount",
/**
* Called when a post is created
*/
OnPostCreate = "onPostCreate",
/**
* Called when a post is deleted
*/
OnPostDelete = "onPostDelete",
/**
* Called when a post is updated
*/
OnPostUpdate = "onPostUpdate",
/**
* Called before the server starts listening
*/
PreServe = "preServe",
/**
* Called after the server stops listening
*/
PostServe = "postServe",
/**
* Called on every HTTP request (before anything else is done)
*/
OnRequestReceive = "onRequestReceive",
/**
* Called on every HTTP request (after it is processed)
*/
OnRequestProcessed = "onRequestProcessed",
/**
* Called on every object received (before it is parsed and added to the database)
*/
OnObjectReceive = "onObjectReceive",
/**
* Called on every object processed (after it is parsed and added to the database)
*/
OnObjectProcessed = "onObjectProcessed",
/**
* Called when signature verification fails on an object
*/
OnCryptoFail = "onCryptoFail",
/**
* Called when signature verification succeeds on an object
*/
OnCryptoSuccess = "onCryptoSuccess",
/**
* Called when a user is banned by another user
*/
OnBan = "onBan",
/**
* Called when a user is suspended by another user
*/
OnSuspend = "onSuspend",
/**
* Called when a user is blocked by another user
*/
OnUserBlock = "onUserBlock",
/**
* Called when a user is muted by another user
*/
OnUserMute = "onUserMute",
/**
* Called when a user is followed by another user
*/
OnUserFollow = "onUserFollow",
/**
* Called when a user registers (before completing email verification)
*/
OnRegister = "onRegister",
/**
* Called when a user finishes registering (after completing email verification)
*/
OnRegisterFinish = "onRegisterFinish",
/**
* Called when a user deletes their account
*/
OnDeleteAccount = "onDeleteAccount",
/**
* Called when a post is created
*/
OnPostCreate = "onPostCreate",
/**
* Called when a post is deleted
*/
OnPostDelete = "onPostDelete",
/**
* Called when a post is updated
*/
OnPostUpdate = "onPostUpdate",
}
export interface ServerStats {
postCount: number;
postCount: number;
}
interface ServerEvents {
[HookTypes.PreServe]: () => void;
[HookTypes.PostServe]: (stats: ServerStats) => void;
[HookTypes.OnRequestReceive]: (req: Request) => void;
[HookTypes.OnRequestProcessed]: (req: Request) => void;
[HookTypes.OnObjectReceive]: (obj: LysandObjectType) => void;
[HookTypes.OnObjectProcessed]: (obj: LysandObjectType) => void;
[HookTypes.OnCryptoFail]: (
req: Request,
obj: LysandObjectType,
author: UserWithRelations,
publicKey: string
) => void;
[HookTypes.OnCryptoSuccess]: (
req: Request,
obj: LysandObjectType,
author: UserWithRelations,
publicKey: string
) => void;
[HookTypes.OnBan]: (
req: Request,
bannedUser: UserWithRelations,
banner: UserWithRelations
) => void;
[HookTypes.OnSuspend]: (
req: Request,
suspendedUser: UserWithRelations,
suspender: UserWithRelations
) => void;
[HookTypes.OnUserBlock]: (
req: Request,
blockedUser: UserWithRelations,
blocker: UserWithRelations
) => void;
[HookTypes.OnUserMute]: (
req: Request,
mutedUser: UserWithRelations,
muter: UserWithRelations
) => void;
[HookTypes.OnUserFollow]: (
req: Request,
followedUser: UserWithRelations,
follower: UserWithRelations
) => void;
[HookTypes.OnRegister]: (req: Request, newUser: UserWithRelations) => void;
[HookTypes.OnDeleteAccount]: (
req: Request,
deletedUser: UserWithRelations
) => void;
[HookTypes.OnPostCreate]: (
req: Request,
newPost: StatusWithRelations,
author: UserWithRelations
) => void;
[HookTypes.OnPostDelete]: (
req: Request,
deletedPost: StatusWithRelations,
deleter: UserWithRelations
) => void;
[HookTypes.OnPostUpdate]: (
req: Request,
updatedPost: StatusWithRelations,
updater: UserWithRelations
) => void;
[HookTypes.PreServe]: () => void;
[HookTypes.PostServe]: (stats: ServerStats) => void;
[HookTypes.OnRequestReceive]: (req: Request) => void;
[HookTypes.OnRequestProcessed]: (req: Request) => void;
[HookTypes.OnObjectReceive]: (obj: LysandObjectType) => void;
[HookTypes.OnObjectProcessed]: (obj: LysandObjectType) => void;
[HookTypes.OnCryptoFail]: (
req: Request,
obj: LysandObjectType,
author: UserWithRelations,
publicKey: string,
) => void;
[HookTypes.OnCryptoSuccess]: (
req: Request,
obj: LysandObjectType,
author: UserWithRelations,
publicKey: string,
) => void;
[HookTypes.OnBan]: (
req: Request,
bannedUser: UserWithRelations,
banner: UserWithRelations,
) => void;
[HookTypes.OnSuspend]: (
req: Request,
suspendedUser: UserWithRelations,
suspender: UserWithRelations,
) => void;
[HookTypes.OnUserBlock]: (
req: Request,
blockedUser: UserWithRelations,
blocker: UserWithRelations,
) => void;
[HookTypes.OnUserMute]: (
req: Request,
mutedUser: UserWithRelations,
muter: UserWithRelations,
) => void;
[HookTypes.OnUserFollow]: (
req: Request,
followedUser: UserWithRelations,
follower: UserWithRelations,
) => void;
[HookTypes.OnRegister]: (req: Request, newUser: UserWithRelations) => void;
[HookTypes.OnDeleteAccount]: (
req: Request,
deletedUser: UserWithRelations,
) => void;
[HookTypes.OnPostCreate]: (
req: Request,
newPost: StatusWithRelations,
author: UserWithRelations,
) => void;
[HookTypes.OnPostDelete]: (
req: Request,
deletedPost: StatusWithRelations,
deleter: UserWithRelations,
) => void;
[HookTypes.OnPostUpdate]: (
req: Request,
updatedPost: StatusWithRelations,
updater: UserWithRelations,
) => void;
}
export class Server extends EventEmitter<ServerEvents> {}

View file

@ -3,7 +3,7 @@ import { config } from "config-manager";
// Proxies all `bunx prisma` commands with an environment variable
process.stdout.write(
`postgresql://${config.database.username}:${config.database.password}@${config.database.host}:${config.database.port}/${config.database.database}\n`
`postgresql://${config.database.username}:${config.database.password}@${config.database.host}:${config.database.port}/${config.database.database}\n`,
);
// Ends

188
routes.ts
View file

@ -5,106 +5,106 @@ import type { APIRouteMeta } from "./types/api";
// This is to allow for compilation of the routes, so that we can minify them and
// node_modules in production
export const rawRoutes = {
"/api/v1/accounts": "./server/api/api/v1/accounts",
"/api/v1/accounts/familiar_followers":
"+api/v1/accounts/familiar_followers/index",
"/api/v1/accounts/relationships":
"./server/api/api/v1/accounts/relationships/index",
"/api/v1/accounts/search": "./server/api/api/v1/accounts/search/index",
"/api/v1/accounts/update_credentials":
"./server/api/api/v1/accounts/update_credentials/index",
"/api/v1/accounts/verify_credentials":
"./server/api/api/v1/accounts/verify_credentials/index",
"/api/v1/apps": "./server/api/api/v1/apps/index",
"/api/v1/apps/verify_credentials":
"./server/api/api/v1/apps/verify_credentials/index",
"/api/v1/blocks": "./server/api/api/v1/blocks/index",
"/api/v1/custom_emojis": "./server/api/api/v1/custom_emojis/index",
"/api/v1/favourites": "./server/api/api/v1/favourites/index",
"/api/v1/follow_requests": "./server/api/api/v1/follow_requests/index",
"/api/v1/instance": "./server/api/api/v1/instance/index",
"/api/v1/media": "./server/api/api/v1/media/index",
"/api/v1/mutes": "./server/api/api/v1/mutes/index",
"/api/v1/notifications": "./server/api/api/v1/notifications/index",
"/api/v1/profile/avatar": "./server/api/api/v1/profile/avatar",
"/api/v1/profile/header": "./server/api/api/v1/profile/header",
"/api/v1/statuses": "./server/api/api/v1/statuses/index",
"/api/v1/timelines/home": "./server/api/api/v1/timelines/home",
"/api/v1/timelines/public": "./server/api/api/v1/timelines/public",
"/api/v2/media": "./server/api/api/v2/media/index",
"/api/v2/search": "./server/api/api/v2/search/index",
"/auth/login": "./server/api/auth/login/index",
"/auth/redirect": "./server/api/auth/redirect/index",
"/nodeinfo/2.0": "./server/api/nodeinfo/2.0/index",
"/oauth/authorize-external": "./server/api/oauth/authorize-external/index",
"/oauth/providers": "./server/api/oauth/providers/index",
"/oauth/token": "./server/api/oauth/token/index",
"/api/v1/accounts/[id]": "./server/api/api/v1/accounts/[id]/index",
"/api/v1/accounts/[id]/block": "./server/api/api/v1/accounts/[id]/block",
"/api/v1/accounts/[id]/follow": "./server/api/api/v1/accounts/[id]/follow",
"/api/v1/accounts/[id]/followers":
"./server/api/api/v1/accounts/[id]/followers",
"/api/v1/accounts/[id]/following":
"./server/api/api/v1/accounts/[id]/following",
"/api/v1/accounts/[id]/mute": "./server/api/api/v1/accounts/[id]/mute",
"/api/v1/accounts/[id]/note": "./server/api/api/v1/accounts/[id]/note",
"/api/v1/accounts/[id]/pin": "./server/api/api/v1/accounts/[id]/pin",
"/api/v1/accounts/[id]/remove_from_followers":
"./server/api/api/v1/accounts/[id]/remove_from_followers",
"/api/v1/accounts/[id]/statuses":
"./server/api/api/v1/accounts/[id]/statuses",
"/api/v1/accounts/[id]/unblock":
"./server/api/api/v1/accounts/[id]/unblock",
"/api/v1/accounts/[id]/unfollow":
"./server/api/api/v1/accounts/[id]/unfollow",
"/api/v1/accounts/[id]/unmute": "./server/api/api/v1/accounts/[id]/unmute",
"/api/v1/accounts/[id]/unpin": "./server/api/api/v1/accounts/[id]/unpin",
"/api/v1/follow_requests/[account_id]/authorize":
"./server/api/api/v1/follow_requests/[account_id]/authorize",
"/api/v1/follow_requests/[account_id]/reject":
"./server/api/api/v1/follow_requests/[account_id]/reject",
"/api/v1/media/[id]": "./server/api/api/v1/media/[id]/index",
"/api/v1/statuses/[id]": "./server/api/api/v1/statuses/[id]/index",
"/api/v1/statuses/[id]/context":
"./server/api/api/v1/statuses/[id]/context",
"/api/v1/statuses/[id]/favourite":
"./server/api/api/v1/statuses/[id]/favourite",
"/api/v1/statuses/[id]/favourited_by":
"./server/api/api/v1/statuses/[id]/favourited_by",
"/api/v1/statuses/[id]/pin": "./server/api/api/v1/statuses/[id]/pin",
"/api/v1/statuses/[id]/reblog": "./server/api/api/v1/statuses/[id]/reblog",
"/api/v1/statuses/[id]/reblogged_by":
"./server/api/api/v1/statuses/[id]/reblogged_by",
"/api/v1/statuses/[id]/source": "./server/api/api/v1/statuses/[id]/source",
"/api/v1/statuses/[id]/unfavourite":
"./server/api/api/v1/statuses/[id]/unfavourite",
"/api/v1/statuses/[id]/unpin": "./server/api/api/v1/statuses/[id]/unpin",
"/api/v1/statuses/[id]/unreblog":
"./server/api/api/v1/statuses/[id]/unreblog",
"/media/[id]": "./server/api/media/[id]/index",
"/oauth/callback/[issuer]": "./server/api/oauth/callback/[issuer]/index",
"/object/[uuid]": "./server/api/object/[uuid]/index",
"/users/[uuid]": "./server/api/users/[uuid]/index",
"/users/[uuid]/inbox": "./server/api/users/[uuid]/inbox/index",
"/users/[uuid]/outbox": "./server/api/users/[uuid]/outbox/index",
"/[...404]": "./server/api/[...404]",
"/api/v1/accounts": "./server/api/api/v1/accounts",
"/api/v1/accounts/familiar_followers":
"+api/v1/accounts/familiar_followers/index",
"/api/v1/accounts/relationships":
"./server/api/api/v1/accounts/relationships/index",
"/api/v1/accounts/search": "./server/api/api/v1/accounts/search/index",
"/api/v1/accounts/update_credentials":
"./server/api/api/v1/accounts/update_credentials/index",
"/api/v1/accounts/verify_credentials":
"./server/api/api/v1/accounts/verify_credentials/index",
"/api/v1/apps": "./server/api/api/v1/apps/index",
"/api/v1/apps/verify_credentials":
"./server/api/api/v1/apps/verify_credentials/index",
"/api/v1/blocks": "./server/api/api/v1/blocks/index",
"/api/v1/custom_emojis": "./server/api/api/v1/custom_emojis/index",
"/api/v1/favourites": "./server/api/api/v1/favourites/index",
"/api/v1/follow_requests": "./server/api/api/v1/follow_requests/index",
"/api/v1/instance": "./server/api/api/v1/instance/index",
"/api/v1/media": "./server/api/api/v1/media/index",
"/api/v1/mutes": "./server/api/api/v1/mutes/index",
"/api/v1/notifications": "./server/api/api/v1/notifications/index",
"/api/v1/profile/avatar": "./server/api/api/v1/profile/avatar",
"/api/v1/profile/header": "./server/api/api/v1/profile/header",
"/api/v1/statuses": "./server/api/api/v1/statuses/index",
"/api/v1/timelines/home": "./server/api/api/v1/timelines/home",
"/api/v1/timelines/public": "./server/api/api/v1/timelines/public",
"/api/v2/media": "./server/api/api/v2/media/index",
"/api/v2/search": "./server/api/api/v2/search/index",
"/auth/login": "./server/api/auth/login/index",
"/auth/redirect": "./server/api/auth/redirect/index",
"/nodeinfo/2.0": "./server/api/nodeinfo/2.0/index",
"/oauth/authorize-external": "./server/api/oauth/authorize-external/index",
"/oauth/providers": "./server/api/oauth/providers/index",
"/oauth/token": "./server/api/oauth/token/index",
"/api/v1/accounts/[id]": "./server/api/api/v1/accounts/[id]/index",
"/api/v1/accounts/[id]/block": "./server/api/api/v1/accounts/[id]/block",
"/api/v1/accounts/[id]/follow": "./server/api/api/v1/accounts/[id]/follow",
"/api/v1/accounts/[id]/followers":
"./server/api/api/v1/accounts/[id]/followers",
"/api/v1/accounts/[id]/following":
"./server/api/api/v1/accounts/[id]/following",
"/api/v1/accounts/[id]/mute": "./server/api/api/v1/accounts/[id]/mute",
"/api/v1/accounts/[id]/note": "./server/api/api/v1/accounts/[id]/note",
"/api/v1/accounts/[id]/pin": "./server/api/api/v1/accounts/[id]/pin",
"/api/v1/accounts/[id]/remove_from_followers":
"./server/api/api/v1/accounts/[id]/remove_from_followers",
"/api/v1/accounts/[id]/statuses":
"./server/api/api/v1/accounts/[id]/statuses",
"/api/v1/accounts/[id]/unblock":
"./server/api/api/v1/accounts/[id]/unblock",
"/api/v1/accounts/[id]/unfollow":
"./server/api/api/v1/accounts/[id]/unfollow",
"/api/v1/accounts/[id]/unmute": "./server/api/api/v1/accounts/[id]/unmute",
"/api/v1/accounts/[id]/unpin": "./server/api/api/v1/accounts/[id]/unpin",
"/api/v1/follow_requests/[account_id]/authorize":
"./server/api/api/v1/follow_requests/[account_id]/authorize",
"/api/v1/follow_requests/[account_id]/reject":
"./server/api/api/v1/follow_requests/[account_id]/reject",
"/api/v1/media/[id]": "./server/api/api/v1/media/[id]/index",
"/api/v1/statuses/[id]": "./server/api/api/v1/statuses/[id]/index",
"/api/v1/statuses/[id]/context":
"./server/api/api/v1/statuses/[id]/context",
"/api/v1/statuses/[id]/favourite":
"./server/api/api/v1/statuses/[id]/favourite",
"/api/v1/statuses/[id]/favourited_by":
"./server/api/api/v1/statuses/[id]/favourited_by",
"/api/v1/statuses/[id]/pin": "./server/api/api/v1/statuses/[id]/pin",
"/api/v1/statuses/[id]/reblog": "./server/api/api/v1/statuses/[id]/reblog",
"/api/v1/statuses/[id]/reblogged_by":
"./server/api/api/v1/statuses/[id]/reblogged_by",
"/api/v1/statuses/[id]/source": "./server/api/api/v1/statuses/[id]/source",
"/api/v1/statuses/[id]/unfavourite":
"./server/api/api/v1/statuses/[id]/unfavourite",
"/api/v1/statuses/[id]/unpin": "./server/api/api/v1/statuses/[id]/unpin",
"/api/v1/statuses/[id]/unreblog":
"./server/api/api/v1/statuses/[id]/unreblog",
"/media/[id]": "./server/api/media/[id]/index",
"/oauth/callback/[issuer]": "./server/api/oauth/callback/[issuer]/index",
"/object/[uuid]": "./server/api/object/[uuid]/index",
"/users/[uuid]": "./server/api/users/[uuid]/index",
"/users/[uuid]/inbox": "./server/api/users/[uuid]/inbox/index",
"/users/[uuid]/outbox": "./server/api/users/[uuid]/outbox/index",
"/[...404]": "./server/api/[...404]",
} as Record<string, string>;
// Returns the route filesystem path when given a URL
export const routeMatcher = new Bun.FileSystemRouter({
style: "nextjs",
dir: process.cwd() + "/server/api",
style: "nextjs",
dir: `${process.cwd()}/server/api`,
});
export const matchRoute = async <T = Record<string, never>>(url: string) => {
const route = routeMatcher.match(url);
if (!route) return { file: null, matchedRoute: null };
const route = routeMatcher.match(url);
if (!route) return { file: null, matchedRoute: null };
return {
file: (await import(rawRoutes[route.name])) as {
default: RouteHandler<T>;
meta: APIRouteMeta;
},
matchedRoute: route,
};
return {
file: (await import(rawRoutes[route.name])) as {
default: RouteHandler<T>;
meta: APIRouteMeta;
},
matchedRoute: route,
};
};

427
server.ts
View file

@ -1,251 +1,246 @@
import { errorResponse, jsonResponse } from "@response";
import type { Config } from "config-manager";
import { matches } from "ip-matching";
import { getFromRequest } from "~database/entities/User";
import { type Config } from "config-manager";
import type { LogManager, MultiLogManager } from "log-manager";
import { LogLevel } from "log-manager";
import { RequestParser } from "request-parser";
import { getFromRequest } from "~database/entities/User";
import { matchRoute } from "~routes";
export const createServer = (
config: Config,
logger: LogManager | MultiLogManager,
isProd: boolean
config: Config,
logger: LogManager | MultiLogManager,
isProd: boolean,
) =>
Bun.serve({
port: config.http.bind_port,
hostname: config.http.bind || "0.0.0.0", // defaults to "0.0.0.0"
async fetch(req) {
// Check for banned IPs
const request_ip = this.requestIP(req)?.address ?? "";
Bun.serve({
port: config.http.bind_port,
hostname: config.http.bind || "0.0.0.0", // defaults to "0.0.0.0"
async fetch(req) {
// Check for banned IPs
const request_ip = this.requestIP(req)?.address ?? "";
for (const ip of config.http.banned_ips) {
try {
if (matches(ip, request_ip)) {
return new Response(undefined, {
status: 403,
statusText: "Forbidden",
});
}
} catch (e) {
console.error(`[-] Error while parsing banned IP "${ip}" `);
throw e;
}
}
for (const ip of config.http.banned_ips) {
try {
if (matches(ip, request_ip)) {
return new Response(undefined, {
status: 403,
statusText: "Forbidden",
});
}
} catch (e) {
console.error(`[-] Error while parsing banned IP "${ip}" `);
throw e;
}
}
// Check for banned user agents (regex)
const ua = req.headers.get("User-Agent") ?? "";
// Check for banned user agents (regex)
const ua = req.headers.get("User-Agent") ?? "";
for (const agent of config.http.banned_user_agents) {
if (new RegExp(agent).test(ua)) {
return new Response(undefined, {
status: 403,
statusText: "Forbidden",
});
}
}
for (const agent of config.http.banned_user_agents) {
if (new RegExp(agent).test(ua)) {
return new Response(undefined, {
status: 403,
statusText: "Forbidden",
});
}
}
if (config.http.bait.enabled) {
// Check for bait IPs
for (const ip of config.http.bait.bait_ips) {
try {
if (matches(ip, request_ip)) {
const file = Bun.file(
config.http.bait.send_file ||
"./pages/beemovie.txt"
);
if (config.http.bait.enabled) {
// Check for bait IPs
for (const ip of config.http.bait.bait_ips) {
try {
if (matches(ip, request_ip)) {
const file = Bun.file(
config.http.bait.send_file ||
"./pages/beemovie.txt",
);
if (await file.exists()) {
return new Response(file);
} else {
await logger.log(
LogLevel.ERROR,
"Server.Bait",
`Bait file not found: ${config.http.bait.send_file}`
);
}
}
} catch (e) {
console.error(
`[-] Error while parsing bait IP "${ip}" `
);
throw e;
}
}
if (await file.exists()) {
return new Response(file);
}
await logger.log(
LogLevel.ERROR,
"Server.Bait",
`Bait file not found: ${config.http.bait.send_file}`,
);
}
} catch (e) {
console.error(
`[-] Error while parsing bait IP "${ip}" `,
);
throw e;
}
}
// Check for bait user agents (regex)
for (const agent of config.http.bait.bait_user_agents) {
console.log(agent);
if (new RegExp(agent).test(ua)) {
const file = Bun.file(
config.http.bait.send_file || "./pages/beemovie.txt"
);
// Check for bait user agents (regex)
for (const agent of config.http.bait.bait_user_agents) {
console.log(agent);
if (new RegExp(agent).test(ua)) {
const file = Bun.file(
config.http.bait.send_file ||
"./pages/beemovie.txt",
);
if (await file.exists()) {
return new Response(file);
} else {
await logger.log(
LogLevel.ERROR,
"Server.Bait",
`Bait file not found: ${config.http.bait.send_file}`
);
}
}
}
}
if (await file.exists()) {
return new Response(file);
}
await logger.log(
LogLevel.ERROR,
"Server.Bait",
`Bait file not found: ${config.http.bait.send_file}`,
);
}
}
}
if (config.logging.log_requests) {
await logger.logRequest(
req,
config.logging.log_ip ? request_ip : undefined,
config.logging.log_requests_verbose
);
}
if (config.logging.log_requests) {
await logger.logRequest(
req,
config.logging.log_ip ? request_ip : undefined,
config.logging.log_requests_verbose,
);
}
if (req.method === "OPTIONS") {
return jsonResponse({});
}
if (req.method === "OPTIONS") {
return jsonResponse({});
}
const { file: filePromise, matchedRoute } = await matchRoute(
req.url
);
const { file: filePromise, matchedRoute } = await matchRoute(
req.url,
);
const file = filePromise;
const file = filePromise;
if (matchedRoute && file == undefined) {
await logger.log(
LogLevel.ERROR,
"Server",
`Route file ${matchedRoute.filePath} not found or not registered in the routes file`
);
if (matchedRoute && file === undefined) {
await logger.log(
LogLevel.ERROR,
"Server",
`Route file ${matchedRoute.filePath} not found or not registered in the routes file`,
);
return errorResponse("Route not found", 500);
}
return errorResponse("Route not found", 500);
}
if (
matchedRoute &&
matchedRoute.name !== "/[...404]" &&
file != undefined
) {
const meta = file.meta;
if (matchedRoute && matchedRoute.name !== "/[...404]" && file) {
const meta = file.meta;
// Check for allowed requests
if (!meta.allowedMethods.includes(req.method as any)) {
return new Response(undefined, {
status: 405,
statusText: `Method not allowed: allowed methods are: ${meta.allowedMethods.join(
", "
)}`,
});
}
// Check for allowed requests
// @ts-expect-error Stupid error
if (!meta.allowedMethods.includes(req.method as string)) {
return new Response(undefined, {
status: 405,
statusText: `Method not allowed: allowed methods are: ${meta.allowedMethods.join(
", ",
)}`,
});
}
// TODO: Check for ratelimits
const auth = await getFromRequest(req);
// TODO: Check for ratelimits
const auth = await getFromRequest(req);
// Check for authentication if required
if (meta.auth.required) {
if (!auth.user) {
return new Response(undefined, {
status: 401,
statusText: "Unauthorized",
});
}
} else if (
(meta.auth.requiredOnMethods ?? []).includes(
req.method as any
)
) {
if (!auth.user) {
return new Response(undefined, {
status: 401,
statusText: "Unauthorized",
});
}
}
// Check for authentication if required
if (meta.auth.required) {
if (!auth.user) {
return new Response(undefined, {
status: 401,
statusText: "Unauthorized",
});
}
} else if (
// @ts-expect-error Stupid error
(meta.auth.requiredOnMethods ?? []).includes(req.method)
) {
if (!auth.user) {
return new Response(undefined, {
status: 401,
statusText: "Unauthorized",
});
}
}
let parsedRequest = {};
let parsedRequest = {};
try {
parsedRequest = await new RequestParser(req).toObject();
} catch (e) {
await logger.logError(
LogLevel.ERROR,
"Server.RouteRequestParser",
e as Error
);
return new Response(undefined, {
status: 400,
statusText: "Bad request",
});
}
try {
parsedRequest = await new RequestParser(req).toObject();
} catch (e) {
await logger.logError(
LogLevel.ERROR,
"Server.RouteRequestParser",
e as Error,
);
return new Response(undefined, {
status: 400,
statusText: "Bad request",
});
}
return await file.default(req.clone(), matchedRoute, {
auth,
parsedRequest,
// To avoid having to rewrite each route
configManager: {
getConfig: () => Promise.resolve(config),
},
});
} else if (matchedRoute?.name === "/[...404]" || !matchedRoute) {
if (new URL(req.url).pathname.startsWith("/api")) {
return errorResponse("Route not found", 404);
}
return await file.default(req.clone(), matchedRoute, {
auth,
parsedRequest,
// To avoid having to rewrite each route
configManager: {
getConfig: () => Promise.resolve(config),
},
});
}
if (matchedRoute?.name === "/[...404]" || !matchedRoute) {
if (new URL(req.url).pathname.startsWith("/api")) {
return errorResponse("Route not found", 404);
}
// Proxy response from Vite at localhost:5173 if in development mode
if (isProd) {
if (new URL(req.url).pathname.startsWith("/assets")) {
const file = Bun.file(
`./pages/dist${new URL(req.url).pathname}`
);
// Proxy response from Vite at localhost:5173 if in development mode
if (isProd) {
if (new URL(req.url).pathname.startsWith("/assets")) {
const file = Bun.file(
`./pages/dist${new URL(req.url).pathname}`,
);
// Serve from pages/dist/assets
if (await file.exists()) {
return new Response(file);
} else return errorResponse("Asset not found", 404);
}
if (new URL(req.url).pathname.startsWith("/api")) {
return errorResponse("Route not found", 404);
}
// Serve from pages/dist/assets
if (await file.exists()) {
return new Response(file);
}
return errorResponse("Asset not found", 404);
}
if (new URL(req.url).pathname.startsWith("/api")) {
return errorResponse("Route not found", 404);
}
const file = Bun.file(`./pages/dist/index.html`);
const file = Bun.file("./pages/dist/index.html");
// Serve from pages/dist
return new Response(file);
} else {
const proxy = await fetch(
req.url.replace(
config.http.base_url,
"http://localhost:5173"
)
).catch(async e => {
await logger.logError(
LogLevel.ERROR,
"Server.Proxy",
e as Error
);
await logger.log(
LogLevel.ERROR,
"Server.Proxy",
`The development Vite server is not running or the route is not found: ${req.url.replace(
config.http.base_url,
"http://localhost:5173"
)}`
);
return errorResponse("Route not found", 404);
});
// Serve from pages/dist
return new Response(file);
}
const proxy = await fetch(
req.url.replace(
config.http.base_url,
"http://localhost:5173",
),
).catch(async (e) => {
await logger.logError(
LogLevel.ERROR,
"Server.Proxy",
e as Error,
);
await logger.log(
LogLevel.ERROR,
"Server.Proxy",
`The development Vite server is not running or the route is not found: ${req.url.replace(
config.http.base_url,
"http://localhost:5173",
)}`,
);
return errorResponse("Route not found", 404);
});
if (
proxy.status !== 404 &&
!(await proxy.clone().text()).includes("404 Not Found")
) {
return proxy;
}
if (
proxy.status !== 404 &&
!(await proxy.clone().text()).includes("404 Not Found")
) {
return proxy;
}
return errorResponse("Route not found", 404);
}
} else {
return errorResponse("Route not found", 404);
}
},
});
return errorResponse("Route not found", 404);
}
return errorResponse("Route not found", 404);
},
});

View file

@ -1,23 +1,22 @@
import { xmlResponse } from "@response";
import { apiRoute, applyConfig } from "@api";
import { xmlResponse } from "@response";
export const meta = applyConfig({
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/host-meta",
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/host-meta",
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const config = await extraData.configManager.getConfig();
const config = await extraData.configManager.getConfig();
return xmlResponse(`
return xmlResponse(`
<?xml version="1.0" encoding="UTF-8"?>
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
<Link rel="lrdd" template="${config.http.base_url}/.well-known/webfinger?resource={uri}"/>

View file

@ -1,43 +1,49 @@
import { jsonResponse } from "@response";
import { apiRoute, applyConfig } from "@api";
import { jsonResponse } from "@response";
export const meta = applyConfig({
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/lysand",
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/lysand",
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const config = await extraData.configManager.getConfig();
// In the format acct:name@example.com
// In the format acct:name@example.com
return jsonResponse({
type: "ServerMetadata",
name: config.instance.name,
version: "0.0.1",
description: config.instance.description,
logo: config.instance.logo ? [
{
content: config.instance.logo,
content_type: `image/${config.instance.logo.split(".")[1]}`,
}
] : undefined,
banner: config.instance.banner ? [
{
content: config.instance.banner,
content_type: `image/${config.instance.banner.split(".")[1]}`,
}
] : undefined,
supported_extensions: [
"org.lysand:custom_emojis"
],
logo: config.instance.logo
? [
{
content: config.instance.logo,
content_type: `image/${
config.instance.logo.split(".")[1]
}`,
},
]
: undefined,
banner: config.instance.banner
? [
{
content: config.instance.banner,
content_type: `image/${
config.instance.banner.split(".")[1]
}`,
},
]
: undefined,
supported_extensions: ["org.lysand:custom_emojis"],
website: "https://lysand.org",
// TODO: Add admins, moderators field
})
})
});
});

View file

@ -1,25 +1,24 @@
import { apiRoute, applyConfig } from "@api";
export const meta = applyConfig({
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/nodeinfo",
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/nodeinfo",
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const config = await extraData.configManager.getConfig();
const config = await extraData.configManager.getConfig();
return new Response("", {
status: 301,
headers: {
Location: `${config.http.base_url}/.well-known/nodeinfo/2.0`,
},
});
return new Response("", {
status: 301,
headers: {
Location: `${config.http.base_url}/.well-known/nodeinfo/2.0`,
},
});
});

View file

@ -1,59 +1,59 @@
import { errorResponse, jsonResponse } from "@response";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/webfinger",
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 60,
},
route: "/.well-known/webfinger",
});
export default apiRoute(async (req, matchedRoute, extraData) => {
// In the format acct:name@example.com
const resource = matchedRoute.query.resource;
const requestedUser = resource.split("acct:")[1];
// In the format acct:name@example.com
const resource = matchedRoute.query.resource;
const requestedUser = resource.split("acct:")[1];
const config = await extraData.configManager.getConfig();
const host = new URL(config.http.base_url).hostname;
const config = await extraData.configManager.getConfig();
const host = new URL(config.http.base_url).hostname;
// Check if user is a local user
if (requestedUser.split("@")[1] !== host) {
return errorResponse("User is a remote user", 404);
}
// Check if user is a local user
if (requestedUser.split("@")[1] !== host) {
return errorResponse("User is a remote user", 404);
}
const user = await client.user.findUnique({
where: { username: requestedUser.split("@")[0] },
});
const user = await client.user.findUnique({
where: { username: requestedUser.split("@")[0] },
});
if (!user) {
return errorResponse("User not found", 404);
}
if (!user) {
return errorResponse("User not found", 404);
}
return jsonResponse({
subject: `acct:${user.username}@${host}`,
return jsonResponse({
subject: `acct:${user.username}@${host}`,
links: [
{
rel: "self",
type: "application/activity+json",
href: `${config.http.base_url}/users/${user.username}/actor`
},
{
rel: "https://webfinger.net/rel/profile-page",
type: "text/html",
href: `${config.http.base_url}/users/${user.username}`
},
{
rel: "self",
type: "application/activity+json; profile=\"https://www.w3.org/ns/activitystreams\"",
href: `${config.http.base_url}/users/${user.username}/actor`
}
]
})
links: [
{
rel: "self",
type: "application/activity+json",
href: `${config.http.base_url}/users/${user.username}/actor`,
},
{
rel: "https://webfinger.net/rel/profile-page",
type: "text/html",
href: `${config.http.base_url}/users/${user.username}`,
},
{
rel: "self",
type: 'application/activity+json; profile="https://www.w3.org/ns/activitystreams"',
href: `${config.http.base_url}/users/${user.username}/actor`,
},
],
});
});

View file

@ -2,20 +2,20 @@ import { apiRoute, applyConfig } from "@api";
import { errorResponse } from "@response";
export const meta = applyConfig({
allowedMethods: ["POST", "GET", "PUT", "PATCH", "DELETE"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 100,
},
route: "/[...404]",
allowedMethods: ["POST", "GET", "PUT", "PATCH", "DELETE"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 100,
},
route: "/[...404]",
});
/**
* Default catch-all route, returns a 404 error.
*/
export default apiRoute(() => {
return errorResponse("This API route does not exist", 404);
return errorResponse("This API route does not exist", 404);
});

View file

@ -1,81 +1,81 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/block",
auth: {
required: true,
oauthPermissions: ["write:blocks"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/block",
auth: {
required: true,
oauthPermissions: ["write:blocks"],
},
});
/**
* Blocks a user
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (!relationship.blocking) {
relationship.blocking = true;
}
if (!relationship.blocking) {
relationship.blocking = true;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
blocking: true,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
blocking: true,
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,99 +1,99 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/follow",
auth: {
required: true,
oauthPermissions: ["write:follows"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/follow",
auth: {
required: true,
oauthPermissions: ["write:follows"],
},
});
/**
* Follow a user
*/
export default apiRoute<{
reblogs?: boolean;
notify?: boolean;
languages?: string[];
reblogs?: boolean;
notify?: boolean;
languages?: string[];
}>(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const { languages, notify, reblogs } = extraData.parsedRequest;
const { languages, notify, reblogs } = extraData.parsedRequest;
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (!relationship.following) {
relationship.following = true;
}
if (reblogs) {
relationship.showingReblogs = true;
}
if (notify) {
relationship.notifying = true;
}
if (languages) {
relationship.languages = languages;
}
if (!relationship.following) {
relationship.following = true;
}
if (reblogs) {
relationship.showingReblogs = true;
}
if (notify) {
relationship.notifying = true;
}
if (languages) {
relationship.languages = languages;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
following: true,
showingReblogs: reblogs ?? false,
notifying: notify ?? false,
languages: languages ?? [],
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
following: true,
showingReblogs: reblogs ?? false,
notifying: notify ?? false,
languages: languages ?? [],
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,82 +1,82 @@
import { apiRoute, applyConfig } from "@api";
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
ratelimits: {
max: 60,
duration: 60,
},
route: "/accounts/:id/followers",
auth: {
required: false,
oauthPermissions: [],
},
allowedMethods: ["GET"],
ratelimits: {
max: 60,
duration: 60,
},
route: "/accounts/:id/followers",
auth: {
required: false,
oauthPermissions: [],
},
});
/**
* Fetch all statuses for a user
*/
export default apiRoute<{
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
}>(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
// TODO: Add pinned
const { max_id, min_id, since_id, limit = 20 } = extraData.parsedRequest;
// TODO: Add pinned
const { max_id, min_id, since_id, limit = 20 } = extraData.parsedRequest;
const user = await client.user.findUnique({
where: { id },
include: userRelations,
});
const user = await client.user.findUnique({
where: { id },
include: userRelations,
});
if (limit < 1 || limit > 40) return errorResponse("Invalid limit", 400);
if (limit < 1 || limit > 40) return errorResponse("Invalid limit", 400);
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
const objects = await client.user.findMany({
where: {
relationships: {
some: {
subjectId: user.id,
following: true,
},
},
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: userRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
const objects = await client.user.findMany({
where: {
relationships: {
some: {
subjectId: user.id,
following: true,
},
},
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: userRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`
);
}
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`,
);
}
return jsonResponse(
await Promise.all(objects.map(object => userToAPI(object))),
200,
{
Link: linkHeader.join(", "),
}
);
return jsonResponse(
await Promise.all(objects.map((object) => userToAPI(object))),
200,
{
Link: linkHeader.join(", "),
},
);
});

View file

@ -1,82 +1,82 @@
import { apiRoute, applyConfig } from "@api";
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
ratelimits: {
max: 60,
duration: 60,
},
route: "/accounts/:id/following",
auth: {
required: false,
oauthPermissions: [],
},
allowedMethods: ["GET"],
ratelimits: {
max: 60,
duration: 60,
},
route: "/accounts/:id/following",
auth: {
required: false,
oauthPermissions: [],
},
});
/**
* Fetch all statuses for a user
*/
export default apiRoute<{
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
}>(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
// TODO: Add pinned
const { max_id, min_id, since_id, limit = 20 } = extraData.parsedRequest;
// TODO: Add pinned
const { max_id, min_id, since_id, limit = 20 } = extraData.parsedRequest;
const user = await client.user.findUnique({
where: { id },
include: userRelations,
});
const user = await client.user.findUnique({
where: { id },
include: userRelations,
});
if (limit < 1 || limit > 40) return errorResponse("Invalid limit", 400);
if (limit < 1 || limit > 40) return errorResponse("Invalid limit", 400);
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
const objects = await client.user.findMany({
where: {
relationshipSubjects: {
some: {
ownerId: user.id,
following: true,
},
},
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: userRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
const objects = await client.user.findMany({
where: {
relationshipSubjects: {
some: {
ownerId: user.id,
following: true,
},
},
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: userRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`
);
}
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`,
);
}
return jsonResponse(
await Promise.all(objects.map(object => userToAPI(object))),
200,
{
Link: linkHeader.join(", "),
}
);
return jsonResponse(
await Promise.all(objects.map((object) => userToAPI(object))),
200,
{
Link: linkHeader.join(", "),
},
);
});

View file

@ -1,46 +1,46 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import type { UserWithRelations } from "~database/entities/User";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id",
auth: {
required: true,
oauthPermissions: [],
},
allowedMethods: ["GET"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id",
auth: {
required: true,
oauthPermissions: [],
},
});
/**
* Fetch a user
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
// Check if ID is valid UUID
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
return errorResponse("Invalid ID", 404);
}
const id = matchedRoute.params.id;
// Check if ID is valid UUID
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
return errorResponse("Invalid ID", 404);
}
const { user } = extraData.auth;
const { user } = extraData.auth;
let foundUser: UserWithRelations | null;
try {
foundUser = await client.user.findUnique({
where: { id },
include: userRelations,
});
} catch (e) {
return errorResponse("Invalid ID", 404);
}
let foundUser: UserWithRelations | null;
try {
foundUser = await client.user.findUnique({
where: { id },
include: userRelations,
});
} catch (e) {
return errorResponse("Invalid ID", 404);
}
if (!foundUser) return errorResponse("User not found", 404);
if (!foundUser) return errorResponse("User not found", 404);
return jsonResponse(userToAPI(foundUser, user?.id === foundUser.id));
return jsonResponse(userToAPI(foundUser, user?.id === foundUser.id));
});

View file

@ -1,93 +1,93 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/mute",
auth: {
required: true,
oauthPermissions: ["write:mutes"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/mute",
auth: {
required: true,
oauthPermissions: ["write:mutes"],
},
});
/**
* Mute a user
*/
export default apiRoute<{
notifications: boolean;
duration: number;
notifications: boolean;
duration: number;
}>(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { notifications, duration } = extraData.parsedRequest;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { notifications, duration } = extraData.parsedRequest;
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (!relationship.muting) {
relationship.muting = true;
}
if (notifications ?? true) {
relationship.mutingNotifications = true;
}
if (!relationship.muting) {
relationship.muting = true;
}
if (notifications ?? true) {
relationship.mutingNotifications = true;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
muting: true,
mutingNotifications: notifications ?? true,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
muting: true,
mutingNotifications: notifications ?? true,
},
});
// TODO: Implement duration
// TODO: Implement duration
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,83 +1,83 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/note",
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/note",
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
});
/**
* Sets a user note
*/
export default apiRoute<{
comment: string;
comment: string;
}>(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const { comment } = extraData.parsedRequest;
const { comment } = extraData.parsedRequest;
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
relationship.note = comment ?? "";
relationship.note = comment ?? "";
await client.relationship.update({
where: { id: relationship.id },
data: {
note: relationship.note,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
note: relationship.note,
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,81 +1,81 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/pin",
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/pin",
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
});
/**
* Pin a user
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (!relationship.endorsed) {
relationship.endorsed = true;
}
if (!relationship.endorsed) {
relationship.endorsed = true;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
endorsed: true,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
endorsed: true,
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,95 +1,95 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/remove_from_followers",
auth: {
required: true,
oauthPermissions: ["write:follows"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/remove_from_followers",
auth: {
required: true,
oauthPermissions: ["write:follows"],
},
});
/**
* Removes an account from your followers list
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (relationship.followedBy) {
relationship.followedBy = false;
}
if (relationship.followedBy) {
relationship.followedBy = false;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
followedBy: false,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
followedBy: false,
},
});
if (user.instanceId === null) {
// Also remove from followers list
await client.relationship.updateMany({
where: {
ownerId: user.id,
subjectId: self.id,
following: true,
},
data: {
following: false,
},
});
}
if (user.instanceId === null) {
// Also remove from followers list
await client.relationship.updateMany({
where: {
ownerId: user.id,
subjectId: self.id,
following: true,
},
data: {
following: false,
},
});
}
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,134 +1,136 @@
import { apiRoute, applyConfig } from "@api";
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { errorResponse, jsonResponse } from "@response";
import { statusToAPI } from "~database/entities/Status";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
import { statusToAPI } from "~database/entities/Status";
import {
userRelations,
statusAndUserRelations,
statusAndUserRelations,
userRelations,
} from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/statuses",
auth: {
required: false,
oauthPermissions: ["read:statuses"],
},
allowedMethods: ["GET"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/statuses",
auth: {
required: false,
oauthPermissions: ["read:statuses"],
},
});
/**
* Fetch all statuses for a user
*/
export default apiRoute<{
max_id?: string;
since_id?: string;
min_id?: string;
limit?: string;
only_media?: boolean;
exclude_replies?: boolean;
exclude_reblogs?: boolean;
// TODO: Add with_muted
pinned?: boolean;
tagged?: string;
max_id?: string;
since_id?: string;
min_id?: string;
limit?: string;
only_media?: boolean;
exclude_replies?: boolean;
exclude_reblogs?: boolean;
// TODO: Add with_muted
pinned?: boolean;
tagged?: string;
}>(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
// TODO: Add pinned
const {
max_id,
min_id,
since_id,
limit = "20",
exclude_reblogs,
pinned,
} = extraData.parsedRequest;
// TODO: Add pinned
const {
max_id,
min_id,
since_id,
limit = "20",
exclude_reblogs,
pinned,
} = extraData.parsedRequest;
const user = await client.user.findUnique({
where: { id },
include: userRelations,
});
const user = await client.user.findUnique({
where: { id },
include: userRelations,
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
if (pinned) {
const objects = await client.status.findMany({
where: {
authorId: id,
isReblog: false,
pinnedBy: {
some: {
id: user.id,
},
},
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: statusAndUserRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
if (pinned) {
const objects = await client.status.findMany({
where: {
authorId: id,
isReblog: false,
pinnedBy: {
some: {
id: user.id,
},
},
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: statusAndUserRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`
);
}
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`,
);
}
return jsonResponse(
await Promise.all(objects.map(status => statusToAPI(status, user))),
200,
{
Link: linkHeader.join(", "),
}
);
}
return jsonResponse(
await Promise.all(
objects.map((status) => statusToAPI(status, user)),
),
200,
{
Link: linkHeader.join(", "),
},
);
}
const objects = await client.status.findMany({
where: {
authorId: id,
isReblog: exclude_reblogs ? true : undefined,
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: statusAndUserRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
const objects = await client.status.findMany({
where: {
authorId: id,
isReblog: exclude_reblogs ? true : undefined,
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
},
include: statusAndUserRelations,
take: Number(limit),
orderBy: {
id: "desc",
},
});
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`
);
}
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`,
);
}
return jsonResponse(
await Promise.all(objects.map(status => statusToAPI(status, user))),
200,
{
Link: linkHeader.join(", "),
}
);
return jsonResponse(
await Promise.all(objects.map((status) => statusToAPI(status, user))),
200,
{
Link: linkHeader.join(", "),
},
);
});

View file

@ -1,81 +1,81 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unblock",
auth: {
required: true,
oauthPermissions: ["write:blocks"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unblock",
auth: {
required: true,
oauthPermissions: ["write:blocks"],
},
});
/**
* Blocks a user
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (relationship.blocking) {
relationship.blocking = false;
}
if (relationship.blocking) {
relationship.blocking = false;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
blocking: false,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
blocking: false,
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,81 +1,81 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unfollow",
auth: {
required: true,
oauthPermissions: ["write:follows"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unfollow",
auth: {
required: true,
oauthPermissions: ["write:follows"],
},
});
/**
* Unfollows a user
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (relationship.following) {
relationship.following = false;
}
if (relationship.following) {
relationship.following = false;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
following: false,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
following: false,
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,83 +1,83 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unmute",
auth: {
required: true,
oauthPermissions: ["write:mutes"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unmute",
auth: {
required: true,
oauthPermissions: ["write:mutes"],
},
});
/**
* Unmute a user
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (relationship.muting) {
relationship.muting = false;
}
if (relationship.muting) {
relationship.muting = false;
}
// TODO: Implement duration
// TODO: Implement duration
await client.relationship.update({
where: { id: relationship.id },
data: {
muting: false,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
muting: false,
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,81 +1,81 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { getRelationshipToOtherUser } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unpin",
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 30,
duration: 60,
},
route: "/accounts/:id/unpin",
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
});
/**
* Unpin a user
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
const user = await client.user.findUnique({
where: { id },
include: {
relationships: {
include: {
owner: true,
subject: true,
},
},
},
});
if (!user) return errorResponse("User not found", 404);
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
// Check if already following
let relationship = await getRelationshipToOtherUser(self, user);
if (!relationship) {
// Create new relationship
if (!relationship) {
// Create new relationship
const newRelationship = await createNewRelationship(self, user);
const newRelationship = await createNewRelationship(self, user);
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
await client.user.update({
where: { id: self.id },
data: {
relationships: {
connect: {
id: newRelationship.id,
},
},
},
});
relationship = newRelationship;
}
relationship = newRelationship;
}
if (relationship.endorsed) {
relationship.endorsed = false;
}
if (relationship.endorsed) {
relationship.endorsed = false;
}
await client.relationship.update({
where: { id: relationship.id },
data: {
endorsed: false,
},
});
await client.relationship.update({
where: { id: relationship.id },
data: {
endorsed: false,
},
});
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,67 +1,67 @@
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/accounts/familiar_followers",
ratelimits: {
max: 5,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:follows"],
},
allowedMethods: ["GET"],
route: "/api/v1/accounts/familiar_followers",
ratelimits: {
max: 5,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:follows"],
},
});
/**
* Find familiar followers (followers of a user that you also follow)
*/
export default apiRoute<{
id: string[];
id: string[];
}>(async (req, matchedRoute, extraData) => {
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const { id: ids } = extraData.parsedRequest;
const { id: ids } = extraData.parsedRequest;
// Minimum id count 1, maximum 10
if (!ids || ids.length < 1 || ids.length > 10) {
return errorResponse("Number of ids must be between 1 and 10", 422);
}
// Minimum id count 1, maximum 10
if (!ids || ids.length < 1 || ids.length > 10) {
return errorResponse("Number of ids must be between 1 and 10", 422);
}
const followersOfIds = await client.user.findMany({
where: {
relationships: {
some: {
subjectId: {
in: ids,
},
following: true,
},
},
},
});
const followersOfIds = await client.user.findMany({
where: {
relationships: {
some: {
subjectId: {
in: ids,
},
following: true,
},
},
},
});
// Find users that you follow in followersOfIds
const output = await client.user.findMany({
where: {
relationships: {
some: {
ownerId: self.id,
subjectId: {
in: followersOfIds.map(f => f.id),
},
following: true,
},
},
},
include: userRelations,
});
// Find users that you follow in followersOfIds
const output = await client.user.findMany({
where: {
relationships: {
some: {
ownerId: self.id,
subjectId: {
in: followersOfIds.map((f) => f.id),
},
following: true,
},
},
},
include: userRelations,
});
return jsonResponse(output.map(o => userToAPI(o)));
return jsonResponse(output.map((o) => userToAPI(o)));
});

View file

@ -1,202 +1,206 @@
import { apiRoute, applyConfig } from "@api";
import { jsonResponse } from "@response";
import { tempmailDomains } from "@tempmail";
import { apiRoute, applyConfig } from "@api";
import ISO6391 from "iso-639-1";
import { client } from "~database/datasource";
import { createNewLocalUser } from "~database/entities/User";
import ISO6391 from "iso-639-1";
export const meta = applyConfig({
allowedMethods: ["POST"],
route: "/api/v1/accounts",
ratelimits: {
max: 2,
duration: 60,
},
auth: {
required: false,
oauthPermissions: ["write:accounts"],
},
allowedMethods: ["POST"],
route: "/api/v1/accounts",
ratelimits: {
max: 2,
duration: 60,
},
auth: {
required: false,
oauthPermissions: ["write:accounts"],
},
});
export default apiRoute<{
username: string;
email: string;
password: string;
agreement: boolean;
locale: string;
reason: string;
username: string;
email: string;
password: string;
agreement: boolean;
locale: string;
reason: string;
}>(async (req, matchedRoute, extraData) => {
// TODO: Add Authorization check
// TODO: Add Authorization check
const body = extraData.parsedRequest;
const body = extraData.parsedRequest;
const config = await extraData.configManager.getConfig();
const config = await extraData.configManager.getConfig();
if (!config.signups.registration) {
return jsonResponse(
{
error: "Registration is disabled",
},
422
);
}
if (!config.signups.registration) {
return jsonResponse(
{
error: "Registration is disabled",
},
422,
);
}
const errors: {
details: Record<
string,
{
error:
| "ERR_BLANK"
| "ERR_INVALID"
| "ERR_TOO_LONG"
| "ERR_TOO_SHORT"
| "ERR_BLOCKED"
| "ERR_TAKEN"
| "ERR_RESERVED"
| "ERR_ACCEPTED"
| "ERR_INCLUSION";
description: string;
}[]
>;
} = {
details: {
password: [],
username: [],
email: [],
agreement: [],
locale: [],
reason: [],
},
};
const errors: {
details: Record<
string,
{
error:
| "ERR_BLANK"
| "ERR_INVALID"
| "ERR_TOO_LONG"
| "ERR_TOO_SHORT"
| "ERR_BLOCKED"
| "ERR_TAKEN"
| "ERR_RESERVED"
| "ERR_ACCEPTED"
| "ERR_INCLUSION";
description: string;
}[]
>;
} = {
details: {
password: [],
username: [],
email: [],
agreement: [],
locale: [],
reason: [],
},
};
// Check if fields are blank
["username", "email", "password", "agreement", "locale", "reason"].forEach(
value => {
// @ts-expect-error Value is always valid
if (!body[value])
errors.details[value].push({
error: "ERR_BLANK",
description: `can't be blank`,
});
}
);
// Check if fields are blank
for (const value of [
"username",
"email",
"password",
"agreement",
"locale",
"reason",
]) {
// @ts-expect-error We don't care about typing here
if (!body[value]) {
errors.details[value].push({
error: "ERR_BLANK",
description: `can't be blank`,
});
}
}
// Check if username is valid
if (!body.username?.match(/^[a-zA-Z0-9_]+$/))
errors.details.username.push({
error: "ERR_INVALID",
description: `must only contain letters, numbers, and underscores`,
});
// Check if username is valid
if (!body.username?.match(/^[a-zA-Z0-9_]+$/))
errors.details.username.push({
error: "ERR_INVALID",
description: "must only contain letters, numbers, and underscores",
});
// Check if username doesnt match filters
if (
config.filters.username_filters.some(filter =>
body.username?.match(filter)
)
) {
errors.details.username.push({
error: "ERR_INVALID",
description: `contains blocked words`,
});
}
// Check if username doesnt match filters
if (
config.filters.username.some((filter) => body.username?.match(filter))
) {
errors.details.username.push({
error: "ERR_INVALID",
description: "contains blocked words",
});
}
// Check if username is too long
if ((body.username?.length ?? 0) > config.validation.max_username_size)
errors.details.username.push({
error: "ERR_TOO_LONG",
description: `is too long (maximum is ${config.validation.max_username_size} characters)`,
});
// Check if username is too long
if ((body.username?.length ?? 0) > config.validation.max_username_size)
errors.details.username.push({
error: "ERR_TOO_LONG",
description: `is too long (maximum is ${config.validation.max_username_size} characters)`,
});
// Check if username is too short
if ((body.username?.length ?? 0) < 3)
errors.details.username.push({
error: "ERR_TOO_SHORT",
description: `is too short (minimum is 3 characters)`,
});
// Check if username is too short
if ((body.username?.length ?? 0) < 3)
errors.details.username.push({
error: "ERR_TOO_SHORT",
description: "is too short (minimum is 3 characters)",
});
// Check if username is reserved
if (config.validation.username_blacklist.includes(body.username ?? ""))
errors.details.username.push({
error: "ERR_RESERVED",
description: `is reserved`,
});
// Check if username is reserved
if (config.validation.username_blacklist.includes(body.username ?? ""))
errors.details.username.push({
error: "ERR_RESERVED",
description: "is reserved",
});
// Check if username is taken
if (await client.user.findFirst({ where: { username: body.username } }))
errors.details.username.push({
error: "ERR_TAKEN",
description: `is already taken`,
});
// Check if username is taken
if (await client.user.findFirst({ where: { username: body.username } }))
errors.details.username.push({
error: "ERR_TAKEN",
description: "is already taken",
});
// Check if email is valid
if (
!body.email?.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)
)
errors.details.email.push({
error: "ERR_INVALID",
description: `must be a valid email address`,
});
// Check if email is valid
if (
!body.email?.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
)
)
errors.details.email.push({
error: "ERR_INVALID",
description: "must be a valid email address",
});
// Check if email is blocked
if (
config.validation.email_blacklist.includes(body.email ?? "") ||
(config.validation.blacklist_tempmail &&
tempmailDomains.domains.includes((body.email ?? "").split("@")[1]))
)
errors.details.email.push({
error: "ERR_BLOCKED",
description: `is from a blocked email provider`,
});
// Check if email is blocked
if (
config.validation.email_blacklist.includes(body.email ?? "") ||
(config.validation.blacklist_tempmail &&
tempmailDomains.domains.includes((body.email ?? "").split("@")[1]))
)
errors.details.email.push({
error: "ERR_BLOCKED",
description: "is from a blocked email provider",
});
// Check if agreement is accepted
if (!body.agreement)
errors.details.agreement.push({
error: "ERR_ACCEPTED",
description: `must be accepted`,
});
// Check if agreement is accepted
if (!body.agreement)
errors.details.agreement.push({
error: "ERR_ACCEPTED",
description: "must be accepted",
});
if (!body.locale)
errors.details.locale.push({
error: "ERR_BLANK",
description: `can't be blank`,
});
if (!body.locale)
errors.details.locale.push({
error: "ERR_BLANK",
description: `can't be blank`,
});
if (!ISO6391.validate(body.locale ?? ""))
errors.details.locale.push({
error: "ERR_INVALID",
description: `must be a valid ISO 639-1 code`,
});
if (!ISO6391.validate(body.locale ?? ""))
errors.details.locale.push({
error: "ERR_INVALID",
description: "must be a valid ISO 639-1 code",
});
// If any errors are present, return them
if (Object.values(errors.details).some(value => value.length > 0)) {
// Error is something like "Validation failed: Password can't be blank, Username must contain only letters, numbers and underscores, Agreement must be accepted"
// If any errors are present, return them
if (Object.values(errors.details).some((value) => value.length > 0)) {
// Error is something like "Validation failed: Password can't be blank, Username must contain only letters, numbers and underscores, Agreement must be accepted"
const errorsText = Object.entries(errors.details)
.map(
([name, errors]) =>
`${name} ${errors
.map(error => error.description)
.join(", ")}`
)
.join(", ");
return jsonResponse(
{
error: `Validation failed: ${errorsText}`,
details: errors.details,
},
422
);
}
const errorsText = Object.entries(errors.details)
.map(
([name, errors]) =>
`${name} ${errors
.map((error) => error.description)
.join(", ")}`,
)
.join(", ");
return jsonResponse(
{
error: `Validation failed: ${errorsText}`,
details: errors.details,
},
422,
);
}
await createNewLocalUser({
username: body.username ?? "",
password: body.password ?? "",
email: body.email ?? "",
});
await createNewLocalUser({
username: body.username ?? "",
password: body.password ?? "",
email: body.email ?? "",
});
return new Response("", {
status: 200,
});
return new Response("", {
status: 200,
});
});

View file

@ -1,66 +1,67 @@
import { errorResponse, jsonResponse } from "@response";
import {
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
import { apiRoute, applyConfig } from "@api";
import type { User } from "@prisma/client";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
createNewRelationship,
relationshipToAPI,
} from "~database/entities/Relationship";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/accounts/relationships",
ratelimits: {
max: 30,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:follows"],
},
allowedMethods: ["GET"],
route: "/api/v1/accounts/relationships",
ratelimits: {
max: 30,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:follows"],
},
});
/**
* Find relationships
*/
export default apiRoute<{
id: string[];
id: string[];
}>(async (req, matchedRoute, extraData) => {
const { user: self } = extraData.auth;
const { user: self } = extraData.auth;
if (!self) return errorResponse("Unauthorized", 401);
if (!self) return errorResponse("Unauthorized", 401);
const { id: ids } = extraData.parsedRequest;
const { id: ids } = extraData.parsedRequest;
// Minimum id count 1, maximum 10
if (!ids || ids.length < 1 || ids.length > 10) {
return errorResponse("Number of ids must be between 1 and 10", 422);
}
// Minimum id count 1, maximum 10
if (!ids || ids.length < 1 || ids.length > 10) {
return errorResponse("Number of ids must be between 1 and 10", 422);
}
const relationships = await client.relationship.findMany({
where: {
ownerId: self.id,
subjectId: {
in: ids,
},
},
});
const relationships = await client.relationship.findMany({
where: {
ownerId: self.id,
subjectId: {
in: ids,
},
},
});
// Find IDs that dont have a relationship
const missingIds = ids.filter(
id => !relationships.some(r => r.subjectId === id)
);
// Find IDs that dont have a relationship
const missingIds = ids.filter(
(id) => !relationships.some((r) => r.subjectId === id),
);
// Create the missing relationships
for (const id of missingIds) {
const relationship = await createNewRelationship(self, { id } as any);
// Create the missing relationships
for (const id of missingIds) {
const relationship = await createNewRelationship(self, { id } as User);
relationships.push(relationship);
}
relationships.push(relationship);
}
// Order in the same order as ids
relationships.sort(
(a, b) => ids.indexOf(a.subjectId) - ids.indexOf(b.subjectId)
);
// Order in the same order as ids
relationships.sort(
(a, b) => ids.indexOf(a.subjectId) - ids.indexOf(b.subjectId),
);
return jsonResponse(relationships.map(r => relationshipToAPI(r)));
return jsonResponse(relationships.map((r) => relationshipToAPI(r)));
});

View file

@ -1,75 +1,75 @@
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/accounts/search",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:accounts"],
},
allowedMethods: ["GET"],
route: "/api/v1/accounts/search",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:accounts"],
},
});
export default apiRoute<{
q?: string;
limit?: number;
offset?: number;
resolve?: boolean;
following?: boolean;
q?: string;
limit?: number;
offset?: number;
resolve?: boolean;
following?: boolean;
}>(async (req, matchedRoute, extraData) => {
// TODO: Add checks for disabled or not email verified accounts
// TODO: Add checks for disabled or not email verified accounts
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const {
following = false,
limit = 40,
offset,
q,
} = extraData.parsedRequest;
const {
following = false,
limit = 40,
offset,
q,
} = extraData.parsedRequest;
if (limit < 1 || limit > 80) {
return errorResponse("Limit must be between 1 and 80", 400);
}
if (limit < 1 || limit > 80) {
return errorResponse("Limit must be between 1 and 80", 400);
}
// TODO: Add WebFinger resolve
// TODO: Add WebFinger resolve
const accounts = await client.user.findMany({
where: {
OR: [
{
displayName: {
contains: q,
},
},
{
username: {
contains: q,
},
},
],
relationshipSubjects: following
? {
some: {
ownerId: user.id,
following,
},
}
: undefined,
},
take: Number(limit),
skip: Number(offset || 0),
include: userRelations,
});
const accounts = await client.user.findMany({
where: {
OR: [
{
displayName: {
contains: q,
},
},
{
username: {
contains: q,
},
},
],
relationshipSubjects: following
? {
some: {
ownerId: user.id,
following,
},
}
: undefined,
},
take: Number(limit),
skip: Number(offset || 0),
include: userRelations,
});
return jsonResponse(accounts.map(acct => userToAPI(acct)));
return jsonResponse(accounts.map((acct) => userToAPI(acct)));
});

View file

@ -1,72 +1,72 @@
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { sanitize } from "isomorphic-dompurify";
import { convertTextToHtml } from "@formatting";
import { errorResponse, jsonResponse } from "@response";
import { sanitizeHtml } from "@sanitization";
import ISO6391 from "iso-639-1";
import { parseEmojis } from "~database/entities/Emoji";
import { client } from "~database/datasource";
import type { APISource } from "~types/entities/source";
import { convertTextToHtml } from "@formatting";
import { sanitize } from "isomorphic-dompurify";
import { MediaBackendType } from "media-manager";
import type { MediaBackend } from "media-manager";
import { client } from "~database/datasource";
import { getUrl } from "~database/entities/Attachment";
import { parseEmojis } from "~database/entities/Emoji";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
import { LocalMediaBackend } from "~packages/media-manager/backends/local";
import { S3MediaBackend } from "~packages/media-manager/backends/s3";
import { getUrl } from "~database/entities/Attachment";
import { userRelations } from "~database/entities/relations";
import type { APISource } from "~types/entities/source";
export const meta = applyConfig({
allowedMethods: ["PATCH"],
route: "/api/v1/accounts/update_credentials",
ratelimits: {
max: 2,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
allowedMethods: ["PATCH"],
route: "/api/v1/accounts/update_credentials",
ratelimits: {
max: 2,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["write:accounts"],
},
});
export default apiRoute<{
display_name: string;
note: string;
avatar: File;
header: File;
locked: string;
bot: string;
discoverable: string;
"source[privacy]": string;
"source[sensitive]": string;
"source[language]": string;
display_name: string;
note: string;
avatar: File;
header: File;
locked: string;
bot: string;
discoverable: string;
"source[privacy]": string;
"source[sensitive]": string;
"source[language]": string;
}>(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const config = await extraData.configManager.getConfig();
const config = await extraData.configManager.getConfig();
const {
display_name,
note,
avatar,
header,
locked,
bot,
discoverable,
"source[privacy]": source_privacy,
"source[sensitive]": source_sensitive,
"source[language]": source_language,
} = extraData.parsedRequest;
const {
display_name,
note,
avatar,
header,
locked,
bot,
discoverable,
"source[privacy]": source_privacy,
"source[sensitive]": source_sensitive,
"source[language]": source_language,
} = extraData.parsedRequest;
const sanitizedNote = await sanitizeHtml(note ?? "");
const sanitizedNote = await sanitizeHtml(note ?? "");
const sanitizedDisplayName = sanitize(display_name ?? "", {
ALLOWED_TAGS: [],
ALLOWED_ATTR: [],
});
const sanitizedDisplayName = sanitize(display_name ?? "", {
ALLOWED_TAGS: [],
ALLOWED_ATTR: [],
});
/* if (!user.source) {
/* if (!user.source) {
user.source = {
privacy: "public",
sensitive: false,
@ -75,191 +75,192 @@ export default apiRoute<{
};
} */
let mediaManager: MediaBackend;
let mediaManager: MediaBackend;
switch (config.media.backend as MediaBackendType) {
case MediaBackendType.LOCAL:
mediaManager = new LocalMediaBackend(config);
break;
case MediaBackendType.S3:
mediaManager = new S3MediaBackend(config);
break;
default:
// TODO: Replace with logger
throw new Error("Invalid media backend");
}
switch (config.media.backend as MediaBackendType) {
case MediaBackendType.LOCAL:
mediaManager = new LocalMediaBackend(config);
break;
case MediaBackendType.S3:
mediaManager = new S3MediaBackend(config);
break;
default:
// TODO: Replace with logger
throw new Error("Invalid media backend");
}
if (display_name) {
// Check if within allowed display name lengths
if (
sanitizedDisplayName.length < 3 ||
sanitizedDisplayName.length > config.validation.max_displayname_size
) {
return errorResponse(
`Display name must be between 3 and ${config.validation.max_displayname_size} characters`,
422
);
}
if (display_name) {
// Check if within allowed display name lengths
if (
sanitizedDisplayName.length < 3 ||
sanitizedDisplayName.length > config.validation.max_displayname_size
) {
return errorResponse(
`Display name must be between 3 and ${config.validation.max_displayname_size} characters`,
422,
);
}
// Check if display name doesnt match filters
if (
config.filters.displayname.some(filter =>
sanitizedDisplayName.match(filter)
)
) {
return errorResponse("Display name contains blocked words", 422);
}
// Check if display name doesnt match filters
if (
config.filters.displayname.some((filter) =>
sanitizedDisplayName.match(filter),
)
) {
return errorResponse("Display name contains blocked words", 422);
}
// Remove emojis
user.emojis = [];
// Remove emojis
user.emojis = [];
user.displayName = sanitizedDisplayName;
}
user.displayName = sanitizedDisplayName;
}
if (note && user.source) {
// Check if within allowed note length
if (sanitizedNote.length > config.validation.max_note_size) {
return errorResponse(
`Note must be less than ${config.validation.max_note_size} characters`,
422
);
}
if (note && user.source) {
// Check if within allowed note length
if (sanitizedNote.length > config.validation.max_note_size) {
return errorResponse(
`Note must be less than ${config.validation.max_note_size} characters`,
422,
);
}
// Check if bio doesnt match filters
if (config.filters.bio.some(filter => sanitizedNote.match(filter))) {
return errorResponse("Bio contains blocked words", 422);
}
// Check if bio doesnt match filters
if (config.filters.bio.some((filter) => sanitizedNote.match(filter))) {
return errorResponse("Bio contains blocked words", 422);
}
(user.source as APISource).note = sanitizedNote;
// TODO: Convert note to HTML
user.note = await convertTextToHtml(sanitizedNote);
}
(user.source as APISource).note = sanitizedNote;
// TODO: Convert note to HTML
user.note = await convertTextToHtml(sanitizedNote);
}
if (source_privacy && user.source) {
// Check if within allowed privacy values
if (
!["public", "unlisted", "private", "direct"].includes(
source_privacy
)
) {
return errorResponse(
"Privacy must be one of public, unlisted, private, or direct",
422
);
}
if (source_privacy && user.source) {
// Check if within allowed privacy values
if (
!["public", "unlisted", "private", "direct"].includes(
source_privacy,
)
) {
return errorResponse(
"Privacy must be one of public, unlisted, private, or direct",
422,
);
}
(user.source as APISource).privacy = source_privacy;
}
(user.source as APISource).privacy = source_privacy;
}
if (source_sensitive && user.source) {
// Check if within allowed sensitive values
if (source_sensitive !== "true" && source_sensitive !== "false") {
return errorResponse("Sensitive must be a boolean", 422);
}
if (source_sensitive && user.source) {
// Check if within allowed sensitive values
if (source_sensitive !== "true" && source_sensitive !== "false") {
return errorResponse("Sensitive must be a boolean", 422);
}
(user.source as APISource).sensitive = source_sensitive === "true";
}
(user.source as APISource).sensitive = source_sensitive === "true";
}
if (source_language && user.source) {
if (!ISO6391.validate(source_language)) {
return errorResponse(
"Language must be a valid ISO 639-1 code",
422
);
}
if (source_language && user.source) {
if (!ISO6391.validate(source_language)) {
return errorResponse(
"Language must be a valid ISO 639-1 code",
422,
);
}
(user.source as APISource).language = source_language;
}
(user.source as APISource).language = source_language;
}
if (avatar) {
// Check if within allowed avatar length (avatar is an image)
if (avatar.size > config.validation.max_avatar_size) {
return errorResponse(
`Avatar must be less than ${config.validation.max_avatar_size} bytes`,
422
);
}
if (avatar) {
// Check if within allowed avatar length (avatar is an image)
if (avatar.size > config.validation.max_avatar_size) {
return errorResponse(
`Avatar must be less than ${config.validation.max_avatar_size} bytes`,
422,
);
}
const { uploadedFile } = await mediaManager.addFile(avatar);
const { uploadedFile } = await mediaManager.addFile(avatar);
user.avatar = getUrl(uploadedFile.name, config);
}
user.avatar = getUrl(uploadedFile.name, config);
}
if (header) {
// Check if within allowed header length (header is an image)
if (header.size > config.validation.max_header_size) {
return errorResponse(
`Header must be less than ${config.validation.max_avatar_size} bytes`,
422
);
}
if (header) {
// Check if within allowed header length (header is an image)
if (header.size > config.validation.max_header_size) {
return errorResponse(
`Header must be less than ${config.validation.max_avatar_size} bytes`,
422,
);
}
const { uploadedFile } = await mediaManager.addFile(header);
const { uploadedFile } = await mediaManager.addFile(header);
user.header = getUrl(uploadedFile.name, config);
}
user.header = getUrl(uploadedFile.name, config);
}
if (locked) {
// Check if locked is a boolean
if (locked !== "true" && locked !== "false") {
return errorResponse("Locked must be a boolean", 422);
}
if (locked) {
// Check if locked is a boolean
if (locked !== "true" && locked !== "false") {
return errorResponse("Locked must be a boolean", 422);
}
user.isLocked = locked === "true";
}
user.isLocked = locked === "true";
}
if (bot) {
// Check if bot is a boolean
if (bot !== "true" && bot !== "false") {
return errorResponse("Bot must be a boolean", 422);
}
if (bot) {
// Check if bot is a boolean
if (bot !== "true" && bot !== "false") {
return errorResponse("Bot must be a boolean", 422);
}
user.isBot = bot === "true";
}
user.isBot = bot === "true";
}
if (discoverable) {
// Check if discoverable is a boolean
if (discoverable !== "true" && discoverable !== "false") {
return errorResponse("Discoverable must be a boolean", 422);
}
if (discoverable) {
// Check if discoverable is a boolean
if (discoverable !== "true" && discoverable !== "false") {
return errorResponse("Discoverable must be a boolean", 422);
}
user.isDiscoverable = discoverable === "true";
}
user.isDiscoverable = discoverable === "true";
}
// Parse emojis
// Parse emojis
const displaynameEmojis = await parseEmojis(sanitizedDisplayName);
const noteEmojis = await parseEmojis(sanitizedNote);
const displaynameEmojis = await parseEmojis(sanitizedDisplayName);
const noteEmojis = await parseEmojis(sanitizedNote);
user.emojis = [...displaynameEmojis, ...noteEmojis];
user.emojis = [...displaynameEmojis, ...noteEmojis];
// Deduplicate emojis
user.emojis = user.emojis.filter(
(emoji, index, self) => self.findIndex(e => e.id === emoji.id) === index
);
// Deduplicate emojis
user.emojis = user.emojis.filter(
(emoji, index, self) =>
self.findIndex((e) => e.id === emoji.id) === index,
);
const output = await client.user.update({
where: { id: user.id },
data: {
displayName: user.displayName,
note: user.note,
avatar: user.avatar,
header: user.header,
isLocked: user.isLocked,
isBot: user.isBot,
isDiscoverable: user.isDiscoverable,
emojis: {
disconnect: user.emojis.map(e => ({
id: e.id,
})),
connect: user.emojis.map(e => ({
id: e.id,
})),
},
source: user.source || undefined,
},
include: userRelations,
});
const output = await client.user.update({
where: { id: user.id },
data: {
displayName: user.displayName,
note: user.note,
avatar: user.avatar,
header: user.header,
isLocked: user.isLocked,
isBot: user.isBot,
isDiscoverable: user.isDiscoverable,
emojis: {
disconnect: user.emojis.map((e) => ({
id: e.id,
})),
connect: user.emojis.map((e) => ({
id: e.id,
})),
},
source: user.source || undefined,
},
include: userRelations,
});
return jsonResponse(userToAPI(output));
return jsonResponse(userToAPI(output));
});

View file

@ -1,28 +1,28 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/accounts/verify_credentials",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:accounts"],
},
allowedMethods: ["GET"],
route: "/api/v1/accounts/verify_credentials",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
oauthPermissions: ["read:accounts"],
},
});
export default apiRoute((req, matchedRoute, extraData) => {
// TODO: Add checks for disabled or not email verified accounts
// TODO: Add checks for disabled or not email verified accounts
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
return jsonResponse({
...userToAPI(user, true),
});
return jsonResponse({
...userToAPI(user, true),
});
});

View file

@ -1,65 +1,65 @@
import { randomBytes } from "node:crypto";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { randomBytes } from "crypto";
import { client } from "~database/datasource";
export const meta = applyConfig({
allowedMethods: ["POST"],
route: "/api/v1/apps",
ratelimits: {
max: 2,
duration: 60,
},
auth: {
required: false,
},
allowedMethods: ["POST"],
route: "/api/v1/apps",
ratelimits: {
max: 2,
duration: 60,
},
auth: {
required: false,
},
});
/**
* Creates a new application to obtain OAuth 2 credentials
*/
export default apiRoute<{
client_name: string;
redirect_uris: string;
scopes: string;
website: string;
client_name: string;
redirect_uris: string;
scopes: string;
website: string;
}>(async (req, matchedRoute, extraData) => {
const { client_name, redirect_uris, scopes, website } =
extraData.parsedRequest;
const { client_name, redirect_uris, scopes, website } =
extraData.parsedRequest;
// Check if redirect URI is a valid URI, and also an absolute URI
if (redirect_uris) {
try {
const redirect_uri = new URL(redirect_uris);
// Check if redirect URI is a valid URI, and also an absolute URI
if (redirect_uris) {
try {
const redirect_uri = new URL(redirect_uris);
if (!redirect_uri.protocol.startsWith("http")) {
return errorResponse(
"Redirect URI must be an absolute URI",
422
);
}
} catch {
return errorResponse("Redirect URI must be a valid URI", 422);
}
}
const application = await client.application.create({
data: {
name: client_name || "",
redirect_uris: redirect_uris || "",
scopes: scopes || "read",
website: website || null,
client_id: randomBytes(32).toString("base64url"),
secret: randomBytes(64).toString("base64url"),
},
});
if (!redirect_uri.protocol.startsWith("http")) {
return errorResponse(
"Redirect URI must be an absolute URI",
422,
);
}
} catch {
return errorResponse("Redirect URI must be a valid URI", 422);
}
}
const application = await client.application.create({
data: {
name: client_name || "",
redirect_uris: redirect_uris || "",
scopes: scopes || "read",
website: website || null,
client_id: randomBytes(32).toString("base64url"),
secret: randomBytes(64).toString("base64url"),
},
});
return jsonResponse({
id: application.id,
name: application.name,
website: application.website,
client_id: application.client_id,
client_secret: application.secret,
redirect_uri: application.redirect_uris,
vapid_link: application.vapid_key,
});
return jsonResponse({
id: application.id,
name: application.name,
website: application.website,
client_id: application.client_id,
client_secret: application.secret,
redirect_uri: application.redirect_uris,
vapid_link: application.vapid_key,
});
});

View file

@ -3,32 +3,32 @@ import { errorResponse, jsonResponse } from "@response";
import { getFromToken } from "~database/entities/Application";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/apps/verify_credentials",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["GET"],
route: "/api/v1/apps/verify_credentials",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
/**
* Returns OAuth2 credentials
*/
export default apiRoute(async (req, matchedRoute, extraData) => {
const { user, token } = extraData.auth;
const application = await getFromToken(token);
const { user, token } = extraData.auth;
const application = await getFromToken(token);
if (!user) return errorResponse("Unauthorized", 401);
if (!application) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
if (!application) return errorResponse("Unauthorized", 401);
return jsonResponse({
name: application.name,
website: application.website,
vapid_key: application.vapid_key,
redirect_uris: application.redirect_uris,
scopes: application.scopes,
});
return jsonResponse({
name: application.name,
website: application.website,
vapid_key: application.vapid_key,
redirect_uris: application.redirect_uris,
scopes: application.scopes,
});
});

View file

@ -1,37 +1,37 @@
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/blocks",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["GET"],
route: "/api/v1/blocks",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const blocks = await client.user.findMany({
where: {
relationshipSubjects: {
some: {
ownerId: user.id,
blocking: true,
},
},
},
include: userRelations,
});
const blocks = await client.user.findMany({
where: {
relationshipSubjects: {
some: {
ownerId: user.id,
blocking: true,
},
},
},
include: userRelations,
});
return jsonResponse(blocks.map(u => userToAPI(u)));
return jsonResponse(blocks.map((u) => userToAPI(u)));
});

View file

@ -4,25 +4,25 @@ import { client } from "~database/datasource";
import { emojiToAPI } from "~database/entities/Emoji";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/custom_emojis",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: false,
},
allowedMethods: ["GET"],
route: "/api/v1/custom_emojis",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: false,
},
});
export default apiRoute(async () => {
const emojis = await client.emoji.findMany({
where: {
instanceId: null,
},
});
const emojis = await client.emoji.findMany({
where: {
instanceId: null,
},
});
return jsonResponse(
await Promise.all(emojis.map(emoji => emojiToAPI(emoji)))
);
return jsonResponse(
await Promise.all(emojis.map((emoji) => emojiToAPI(emoji))),
);
});

View file

@ -1,74 +1,74 @@
import { errorResponse, jsonResponse } from "@response";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { statusAndUserRelations } from "~database/entities/relations";
import { statusToAPI } from "~database/entities/Status";
import { statusAndUserRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/favourites",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["GET"],
route: "/api/v1/favourites",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
export default apiRoute<{
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
}>(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
const { limit = 20, max_id, min_id, since_id } = extraData.parsedRequest;
const { limit = 20, max_id, min_id, since_id } = extraData.parsedRequest;
if (limit < 1 || limit > 40) {
return errorResponse("Limit must be between 1 and 40", 400);
}
if (limit < 1 || limit > 40) {
return errorResponse("Limit must be between 1 and 40", 400);
}
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const objects = await client.status.findMany({
where: {
id: {
lt: max_id ?? undefined,
gte: since_id ?? undefined,
gt: min_id ?? undefined,
},
likes: {
some: {
likerId: user.id,
},
},
},
include: statusAndUserRelations,
take: limit,
orderBy: {
id: "desc",
},
});
const objects = await client.status.findMany({
where: {
id: {
lt: max_id ?? undefined,
gte: since_id ?? undefined,
gt: min_id ?? undefined,
},
likes: {
some: {
likerId: user.id,
},
},
},
include: statusAndUserRelations,
take: limit,
orderBy: {
id: "desc",
},
});
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`
);
}
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`,
);
}
return jsonResponse(
await Promise.all(
objects.map(async status => statusToAPI(status, user))
),
200,
{
Link: linkHeader.join(", "),
}
);
return jsonResponse(
await Promise.all(
objects.map(async (status) => statusToAPI(status, user)),
),
200,
{
Link: linkHeader.join(", "),
},
);
});

View file

@ -1,75 +1,75 @@
import { errorResponse, jsonResponse } from "@response";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
checkForBidirectionalRelationships,
relationshipToAPI,
checkForBidirectionalRelationships,
relationshipToAPI,
} from "~database/entities/Relationship";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["POST"],
route: "/api/v1/follow_requests/:account_id/authorize",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["POST"],
route: "/api/v1/follow_requests/:account_id/authorize",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const { account_id } = matchedRoute.params;
const { account_id } = matchedRoute.params;
const account = await client.user.findUnique({
where: {
id: account_id,
},
include: userRelations,
});
const account = await client.user.findUnique({
where: {
id: account_id,
},
include: userRelations,
});
if (!account) return errorResponse("Account not found", 404);
if (!account) return errorResponse("Account not found", 404);
// Check if there is a relationship on both sides
await checkForBidirectionalRelationships(user, account);
// Check if there is a relationship on both sides
await checkForBidirectionalRelationships(user, account);
// Authorize follow request
await client.relationship.updateMany({
where: {
subjectId: user.id,
ownerId: account.id,
requested: true,
},
data: {
requested: false,
following: true,
},
});
// Authorize follow request
await client.relationship.updateMany({
where: {
subjectId: user.id,
ownerId: account.id,
requested: true,
},
data: {
requested: false,
following: true,
},
});
// Update followedBy for other user
await client.relationship.updateMany({
where: {
subjectId: account.id,
ownerId: user.id,
},
data: {
followedBy: true,
},
});
// Update followedBy for other user
await client.relationship.updateMany({
where: {
subjectId: account.id,
ownerId: user.id,
},
data: {
followedBy: true,
},
});
const relationship = await client.relationship.findFirst({
where: {
subjectId: account.id,
ownerId: user.id,
},
});
const relationship = await client.relationship.findFirst({
where: {
subjectId: account.id,
ownerId: user.id,
},
});
if (!relationship) return errorResponse("Relationship not found", 404);
if (!relationship) return errorResponse("Relationship not found", 404);
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,63 +1,63 @@
import { errorResponse, jsonResponse } from "@response";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import {
checkForBidirectionalRelationships,
relationshipToAPI,
checkForBidirectionalRelationships,
relationshipToAPI,
} from "~database/entities/Relationship";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["POST"],
route: "/api/v1/follow_requests/:account_id/reject",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["POST"],
route: "/api/v1/follow_requests/:account_id/reject",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const { account_id } = matchedRoute.params;
const { account_id } = matchedRoute.params;
const account = await client.user.findUnique({
where: {
id: account_id,
},
include: userRelations,
});
const account = await client.user.findUnique({
where: {
id: account_id,
},
include: userRelations,
});
if (!account) return errorResponse("Account not found", 404);
if (!account) return errorResponse("Account not found", 404);
// Check if there is a relationship on both sides
await checkForBidirectionalRelationships(user, account);
// Check if there is a relationship on both sides
await checkForBidirectionalRelationships(user, account);
// Reject follow request
await client.relationship.updateMany({
where: {
subjectId: user.id,
ownerId: account.id,
requested: true,
},
data: {
requested: false,
},
});
// Reject follow request
await client.relationship.updateMany({
where: {
subjectId: user.id,
ownerId: account.id,
requested: true,
},
data: {
requested: false,
},
});
const relationship = await client.relationship.findFirst({
where: {
subjectId: account.id,
ownerId: user.id,
},
});
const relationship = await client.relationship.findFirst({
where: {
subjectId: account.id,
ownerId: user.id,
},
});
if (!relationship) return errorResponse("Relationship not found", 404);
if (!relationship) return errorResponse("Relationship not found", 404);
return jsonResponse(relationshipToAPI(relationship));
return jsonResponse(relationshipToAPI(relationship));
});

View file

@ -1,73 +1,73 @@
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/follow_requests",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["GET"],
route: "/api/v1/follow_requests",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
export default apiRoute<{
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
}>(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
const { limit = 20, max_id, min_id, since_id } = extraData.parsedRequest;
const { limit = 20, max_id, min_id, since_id } = extraData.parsedRequest;
if (limit < 1 || limit > 40) {
return errorResponse("Limit must be between 1 and 40", 400);
}
if (limit < 1 || limit > 40) {
return errorResponse("Limit must be between 1 and 40", 400);
}
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const objects = await client.user.findMany({
where: {
id: {
lt: max_id ?? undefined,
gte: since_id ?? undefined,
gt: min_id ?? undefined,
},
relationships: {
some: {
subjectId: user.id,
requested: true,
},
},
},
include: userRelations,
take: limit,
orderBy: {
id: "desc",
},
});
const objects = await client.user.findMany({
where: {
id: {
lt: max_id ?? undefined,
gte: since_id ?? undefined,
gt: min_id ?? undefined,
},
relationships: {
some: {
subjectId: user.id,
requested: true,
},
},
},
include: userRelations,
take: limit,
orderBy: {
id: "desc",
},
});
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`
);
}
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects.at(-1)?.id}>; rel="next"`,
`<${urlWithoutQuery}?min_id=${objects[0].id}>; rel="prev"`,
);
}
return jsonResponse(
objects.map(user => userToAPI(user)),
200,
{
Link: linkHeader.join(", "),
}
);
return jsonResponse(
objects.map((user) => userToAPI(user)),
200,
{
Link: linkHeader.join(", "),
},
);
});

View file

@ -2,157 +2,157 @@ import { apiRoute, applyConfig } from "@api";
import { jsonResponse } from "@response";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import type { APIInstance } from "~types/entities/instance";
import manifest from "~package.json";
import { userRelations } from "~database/entities/relations";
import manifest from "~package.json";
import type { APIInstance } from "~types/entities/instance";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/instance",
ratelimits: {
max: 300,
duration: 60,
},
auth: {
required: false,
},
allowedMethods: ["GET"],
route: "/api/v1/instance",
ratelimits: {
max: 300,
duration: 60,
},
auth: {
required: false,
},
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const config = await extraData.configManager.getConfig();
const config = await extraData.configManager.getConfig();
// Get software version from package.json
const version = manifest.version;
// Get software version from package.json
const version = manifest.version;
const statusCount = await client.status.count({
where: {
instanceId: null,
},
});
const userCount = await client.user.count({
where: {
instanceId: null,
},
});
const statusCount = await client.status.count({
where: {
instanceId: null,
},
});
const userCount = await client.user.count({
where: {
instanceId: null,
},
});
// Get the first created admin user
const contactAccount = await client.user.findFirst({
where: {
instanceId: null,
isAdmin: true,
},
orderBy: {
id: "asc",
},
include: userRelations,
});
// Get the first created admin user
const contactAccount = await client.user.findFirst({
where: {
instanceId: null,
isAdmin: true,
},
orderBy: {
id: "asc",
},
include: userRelations,
});
// Get user that have posted once in the last 30 days
const monthlyActiveUsers = await client.user.count({
where: {
instanceId: null,
statuses: {
some: {
createdAt: {
gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
},
},
},
},
});
// Get user that have posted once in the last 30 days
const monthlyActiveUsers = await client.user.count({
where: {
instanceId: null,
statuses: {
some: {
createdAt: {
gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
},
},
},
},
});
const knownDomainsCount = await client.instance.count();
const knownDomainsCount = await client.instance.count();
// TODO: fill in more values
return jsonResponse({
approval_required: false,
configuration: {
media_attachments: {
image_matrix_limit: config.validation.max_media_attachments,
image_size_limit: config.validation.max_media_size,
supported_mime_types: config.validation.allowed_mime_types,
video_frame_limit: 60,
video_matrix_limit: 10,
video_size_limit: config.validation.max_media_size,
},
polls: {
max_characters_per_option:
config.validation.max_poll_option_size,
max_expiration: config.validation.max_poll_duration,
max_options: config.validation.max_poll_options,
min_expiration: 60,
},
statuses: {
characters_reserved_per_url: 0,
max_characters: config.validation.max_note_size,
max_media_attachments: config.validation.max_media_attachments,
supported_mime_types: [
"text/plain",
"text/markdown",
"text/html",
"text/x.misskeymarkdown",
],
},
},
description: "A test instance",
email: "",
invites_enabled: false,
registrations: config.signups.registration,
languages: ["en"],
rules: config.signups.rules.map((r, index) => ({
id: String(index),
text: r,
})),
stats: {
domain_count: knownDomainsCount,
status_count: statusCount,
user_count: userCount,
},
thumbnail: "",
tos_url: config.signups.tos_url,
title: "Test Instance",
uri: new URL(config.http.base_url).hostname,
urls: {
streaming_api: "",
},
version: `4.2.0+glitch (compatible; Lysand ${version}})`,
max_toot_chars: config.validation.max_note_size,
pleroma: {
metadata: {
// account_activation_required: false,
features: [
"pleroma_api",
"akkoma_api",
"mastodon_api",
// "mastodon_api_streaming",
// "polls",
// "v2_suggestions",
// "pleroma_explicit_addressing",
// "shareable_emoji_packs",
// "multifetch",
// "pleroma:api/v1/notifications:include_types_filter",
"quote_posting",
"editing",
// "bubble_timeline",
// "relay",
// "pleroma_emoji_reactions",
// "exposable_reactions",
// "profile_directory",
// "custom_emoji_reactions",
// "pleroma:get:main/ostatus",
],
post_formats: [
"text/plain",
"text/html",
"text/markdown",
"text/x.misskeymarkdown",
],
privileged_staff: false,
},
stats: {
mau: monthlyActiveUsers,
},
},
contact_account: contactAccount ? userToAPI(contactAccount) : null,
} as APIInstance);
// TODO: fill in more values
return jsonResponse({
approval_required: false,
configuration: {
media_attachments: {
image_matrix_limit: config.validation.max_media_attachments,
image_size_limit: config.validation.max_media_size,
supported_mime_types: config.validation.allowed_mime_types,
video_frame_limit: 60,
video_matrix_limit: 10,
video_size_limit: config.validation.max_media_size,
},
polls: {
max_characters_per_option:
config.validation.max_poll_option_size,
max_expiration: config.validation.max_poll_duration,
max_options: config.validation.max_poll_options,
min_expiration: 60,
},
statuses: {
characters_reserved_per_url: 0,
max_characters: config.validation.max_note_size,
max_media_attachments: config.validation.max_media_attachments,
supported_mime_types: [
"text/plain",
"text/markdown",
"text/html",
"text/x.misskeymarkdown",
],
},
},
description: "A test instance",
email: "",
invites_enabled: false,
registrations: config.signups.registration,
languages: ["en"],
rules: config.signups.rules.map((r, index) => ({
id: String(index),
text: r,
})),
stats: {
domain_count: knownDomainsCount,
status_count: statusCount,
user_count: userCount,
},
thumbnail: "",
tos_url: config.signups.tos_url,
title: "Test Instance",
uri: new URL(config.http.base_url).hostname,
urls: {
streaming_api: "",
},
version: `4.2.0+glitch (compatible; Lysand ${version}})`,
max_toot_chars: config.validation.max_note_size,
pleroma: {
metadata: {
// account_activation_required: false,
features: [
"pleroma_api",
"akkoma_api",
"mastodon_api",
// "mastodon_api_streaming",
// "polls",
// "v2_suggestions",
// "pleroma_explicit_addressing",
// "shareable_emoji_packs",
// "multifetch",
// "pleroma:api/v1/notifications:include_types_filter",
"quote_posting",
"editing",
// "bubble_timeline",
// "relay",
// "pleroma_emoji_reactions",
// "exposable_reactions",
// "profile_directory",
// "custom_emoji_reactions",
// "pleroma:get:main/ostatus",
],
post_formats: [
"text/plain",
"text/html",
"text/markdown",
"text/x.misskeymarkdown",
],
privileged_staff: false,
},
stats: {
mau: monthlyActiveUsers,
},
},
contact_account: contactAccount ? userToAPI(contactAccount) : null,
} as APIInstance);
});

View file

@ -1,109 +1,108 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { attachmentToAPI, getUrl } from "~database/entities/Attachment";
import type { MediaBackend } from "media-manager";
import { MediaBackendType } from "media-manager";
import { client } from "~database/datasource";
import { attachmentToAPI, getUrl } from "~database/entities/Attachment";
import { LocalMediaBackend } from "~packages/media-manager/backends/local";
import { S3MediaBackend } from "~packages/media-manager/backends/s3";
export const meta = applyConfig({
allowedMethods: ["GET", "PUT"],
ratelimits: {
max: 10,
duration: 60,
},
route: "/api/v1/media/:id",
auth: {
required: true,
oauthPermissions: ["write:media"],
},
allowedMethods: ["GET", "PUT"],
ratelimits: {
max: 10,
duration: 60,
},
route: "/api/v1/media/:id",
auth: {
required: true,
oauthPermissions: ["write:media"],
},
});
/**
* Get media information
*/
export default apiRoute<{
thumbnail?: File;
description?: string;
focus?: string;
thumbnail?: File;
description?: string;
focus?: string;
}>(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) {
return errorResponse("Unauthorized", 401);
}
if (!user) {
return errorResponse("Unauthorized", 401);
}
const id = matchedRoute.params.id;
const id = matchedRoute.params.id;
const attachment = await client.attachment.findUnique({
where: {
id,
},
});
const attachment = await client.attachment.findUnique({
where: {
id,
},
});
if (!attachment) {
return errorResponse("Media not found", 404);
}
if (!attachment) {
return errorResponse("Media not found", 404);
}
const config = await extraData.configManager.getConfig();
const config = await extraData.configManager.getConfig();
switch (req.method) {
case "GET": {
if (attachment.url) {
return jsonResponse(attachmentToAPI(attachment));
} else {
return new Response(null, {
status: 206,
});
}
}
case "PUT": {
const { description, thumbnail } = extraData.parsedRequest;
switch (req.method) {
case "GET": {
if (attachment.url) {
return jsonResponse(attachmentToAPI(attachment));
}
return new Response(null, {
status: 206,
});
}
case "PUT": {
const { description, thumbnail } = extraData.parsedRequest;
let thumbnailUrl = attachment.thumbnail_url;
let thumbnailUrl = attachment.thumbnail_url;
let mediaManager: MediaBackend;
let mediaManager: MediaBackend;
switch (config.media.backend as MediaBackendType) {
case MediaBackendType.LOCAL:
mediaManager = new LocalMediaBackend(config);
break;
case MediaBackendType.S3:
mediaManager = new S3MediaBackend(config);
break;
default:
// TODO: Replace with logger
throw new Error("Invalid media backend");
}
switch (config.media.backend as MediaBackendType) {
case MediaBackendType.LOCAL:
mediaManager = new LocalMediaBackend(config);
break;
case MediaBackendType.S3:
mediaManager = new S3MediaBackend(config);
break;
default:
// TODO: Replace with logger
throw new Error("Invalid media backend");
}
if (thumbnail) {
const { uploadedFile } = await mediaManager.addFile(thumbnail);
thumbnailUrl = getUrl(uploadedFile.name, config);
}
if (thumbnail) {
const { uploadedFile } = await mediaManager.addFile(thumbnail);
thumbnailUrl = getUrl(uploadedFile.name, config);
}
const descriptionText = description || attachment.description;
const descriptionText = description || attachment.description;
if (
descriptionText !== attachment.description ||
thumbnailUrl !== attachment.thumbnail_url
) {
const newAttachment = await client.attachment.update({
where: {
id,
},
data: {
description: descriptionText,
thumbnail_url: thumbnailUrl,
},
});
if (
descriptionText !== attachment.description ||
thumbnailUrl !== attachment.thumbnail_url
) {
const newAttachment = await client.attachment.update({
where: {
id,
},
data: {
description: descriptionText,
thumbnail_url: thumbnailUrl,
},
});
return jsonResponse(attachmentToAPI(newAttachment));
}
return jsonResponse(attachmentToAPI(newAttachment));
}
return jsonResponse(attachmentToAPI(attachment));
}
}
return jsonResponse(attachmentToAPI(attachment));
}
}
return errorResponse("Method not allowed", 405);
return errorResponse("Method not allowed", 405);
});

View file

@ -1,136 +1,136 @@
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { encode } from "blurhash";
import sharp from "sharp";
import { attachmentToAPI, getUrl } from "~database/entities/Attachment";
import { MediaBackendType } from "media-manager";
import type { MediaBackend } from "media-manager";
import sharp from "sharp";
import { client } from "~database/datasource";
import { attachmentToAPI, getUrl } from "~database/entities/Attachment";
import { LocalMediaBackend } from "~packages/media-manager/backends/local";
import { S3MediaBackend } from "~packages/media-manager/backends/s3";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 10,
duration: 60,
},
route: "/api/v1/media",
auth: {
required: true,
oauthPermissions: ["write:media"],
},
allowedMethods: ["POST"],
ratelimits: {
max: 10,
duration: 60,
},
route: "/api/v1/media",
auth: {
required: true,
oauthPermissions: ["write:media"],
},
});
/**
* Upload new media
*/
export default apiRoute<{
file: File;
thumbnail?: File;
description?: string;
// TODO: Add focus
focus?: string;
file: File;
thumbnail?: File;
description?: string;
// TODO: Add focus
focus?: string;
}>(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) {
return errorResponse("Unauthorized", 401);
}
if (!user) {
return errorResponse("Unauthorized", 401);
}
const { file, thumbnail, description } = extraData.parsedRequest;
const { file, thumbnail, description } = extraData.parsedRequest;
if (!file) {
return errorResponse("No file provided", 400);
}
if (!file) {
return errorResponse("No file provided", 400);
}
const config = await extraData.configManager.getConfig();
const config = await extraData.configManager.getConfig();
if (file.size > config.validation.max_media_size) {
return errorResponse(
`File too large, max size is ${config.validation.max_media_size} bytes`,
413
);
}
if (file.size > config.validation.max_media_size) {
return errorResponse(
`File too large, max size is ${config.validation.max_media_size} bytes`,
413,
);
}
if (
config.validation.enforce_mime_types &&
!config.validation.allowed_mime_types.includes(file.type)
) {
return errorResponse("Invalid file type", 415);
}
if (
config.validation.enforce_mime_types &&
!config.validation.allowed_mime_types.includes(file.type)
) {
return errorResponse("Invalid file type", 415);
}
if (
description &&
description.length > config.validation.max_media_description_size
) {
return errorResponse(
`Description too long, max length is ${config.validation.max_media_description_size} characters`,
413
);
}
if (
description &&
description.length > config.validation.max_media_description_size
) {
return errorResponse(
`Description too long, max length is ${config.validation.max_media_description_size} characters`,
413,
);
}
const sha256 = new Bun.SHA256();
const sha256 = new Bun.SHA256();
const isImage = file.type.startsWith("image/");
const isImage = file.type.startsWith("image/");
const metadata = isImage
? await sharp(await file.arrayBuffer()).metadata()
: null;
const metadata = isImage
? await sharp(await file.arrayBuffer()).metadata()
: null;
const blurhash = isImage
? encode(
new Uint8ClampedArray(await file.arrayBuffer()),
metadata?.width ?? 0,
metadata?.height ?? 0,
4,
4
)
: null;
const blurhash = isImage
? encode(
new Uint8ClampedArray(await file.arrayBuffer()),
metadata?.width ?? 0,
metadata?.height ?? 0,
4,
4,
)
: null;
let url = "";
let url = "";
let mediaManager: MediaBackend;
let mediaManager: MediaBackend;
switch (config.media.backend as MediaBackendType) {
case MediaBackendType.LOCAL:
mediaManager = new LocalMediaBackend(config);
break;
case MediaBackendType.S3:
mediaManager = new S3MediaBackend(config);
break;
default:
// TODO: Replace with logger
throw new Error("Invalid media backend");
}
switch (config.media.backend as MediaBackendType) {
case MediaBackendType.LOCAL:
mediaManager = new LocalMediaBackend(config);
break;
case MediaBackendType.S3:
mediaManager = new S3MediaBackend(config);
break;
default:
// TODO: Replace with logger
throw new Error("Invalid media backend");
}
const { uploadedFile } = await mediaManager.addFile(file);
const { uploadedFile } = await mediaManager.addFile(file);
url = getUrl(uploadedFile.name, config);
url = getUrl(uploadedFile.name, config);
let thumbnailUrl = "";
let thumbnailUrl = "";
if (thumbnail) {
const { uploadedFile } = await mediaManager.addFile(thumbnail);
if (thumbnail) {
const { uploadedFile } = await mediaManager.addFile(thumbnail);
thumbnailUrl = getUrl(uploadedFile.name, config);
}
thumbnailUrl = getUrl(uploadedFile.name, config);
}
const newAttachment = await client.attachment.create({
data: {
url,
thumbnail_url: thumbnailUrl,
sha256: sha256.update(await file.arrayBuffer()).digest("hex"),
mime_type: file.type,
description: description ?? "",
size: file.size,
blurhash: blurhash ?? undefined,
width: metadata?.width ?? undefined,
height: metadata?.height ?? undefined,
},
});
const newAttachment = await client.attachment.create({
data: {
url,
thumbnail_url: thumbnailUrl,
sha256: sha256.update(await file.arrayBuffer()).digest("hex"),
mime_type: file.type,
description: description ?? "",
size: file.size,
blurhash: blurhash ?? undefined,
width: metadata?.width ?? undefined,
height: metadata?.height ?? undefined,
},
});
// TODO: Add job to process videos and other media
// TODO: Add job to process videos and other media
return jsonResponse(attachmentToAPI(newAttachment));
return jsonResponse(attachmentToAPI(newAttachment));
});

View file

@ -1,37 +1,37 @@
import { errorResponse, jsonResponse } from "@response";
import { userToAPI } from "~database/entities/User";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { userToAPI } from "~database/entities/User";
import { userRelations } from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/mutes",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["GET"],
route: "/api/v1/mutes",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
export default apiRoute(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const blocks = await client.user.findMany({
where: {
relationshipSubjects: {
some: {
ownerId: user.id,
muting: true,
},
},
},
include: userRelations,
});
const blocks = await client.user.findMany({
where: {
relationshipSubjects: {
some: {
ownerId: user.id,
muting: true,
},
},
},
include: userRelations,
});
return jsonResponse(blocks.map(u => userToAPI(u)));
return jsonResponse(blocks.map((u) => userToAPI(u)));
});

View file

@ -1,102 +1,102 @@
import { errorResponse, jsonResponse } from "@response";
import { apiRoute, applyConfig } from "@api";
import { errorResponse, jsonResponse } from "@response";
import { client } from "~database/datasource";
import { notificationToAPI } from "~database/entities/Notification";
import {
userRelations,
statusAndUserRelations,
statusAndUserRelations,
userRelations,
} from "~database/entities/relations";
export const meta = applyConfig({
allowedMethods: ["GET"],
route: "/api/v1/notifications",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
allowedMethods: ["GET"],
route: "/api/v1/notifications",
ratelimits: {
max: 100,
duration: 60,
},
auth: {
required: true,
},
});
export default apiRoute<{
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
exclude_types?: string[];
types?: string[];
account_id?: string;
max_id?: string;
since_id?: string;
min_id?: string;
limit?: number;
exclude_types?: string[];
types?: string[];
account_id?: string;
}>(async (req, matchedRoute, extraData) => {
const { user } = extraData.auth;
const { user } = extraData.auth;
if (!user) return errorResponse("Unauthorized", 401);
if (!user) return errorResponse("Unauthorized", 401);
const {
account_id,
exclude_types,
limit = 15,
max_id,
min_id,
since_id,
types,
} = extraData.parsedRequest;
const {
account_id,
exclude_types,
limit = 15,
max_id,
min_id,
since_id,
types,
} = extraData.parsedRequest;
if (limit > 30) return errorResponse("Limit too high", 400);
if (limit > 30) return errorResponse("Limit too high", 400);
if (limit <= 0) return errorResponse("Limit too low", 400);
if (limit <= 0) return errorResponse("Limit too low", 400);
if (types && exclude_types) {
return errorResponse("Can't use both types and exclude_types", 400);
}
if (types && exclude_types) {
return errorResponse("Can't use both types and exclude_types", 400);
}
const objects = await client.notification.findMany({
where: {
notifiedId: user.id,
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
type: {
in: types,
notIn: exclude_types,
},
accountId: account_id,
},
include: {
account: {
include: userRelations,
},
status: {
include: statusAndUserRelations,
},
},
orderBy: {
id: "desc",
},
take: limit,
});
const objects = await client.notification.findMany({
where: {
notifiedId: user.id,
id: {
lt: max_id,
gt: min_id,
gte: since_id,
},
type: {
in: types,
notIn: exclude_types,
},
accountId: account_id,
},
include: {
account: {
include: userRelations,
},
status: {
include: statusAndUserRelations,
},
},
orderBy: {
id: "desc",
},
take: limit,
});
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects[0].id}&limit=${limit}>; rel="next"`
);
linkHeader.push(
`<${urlWithoutQuery}?since_id=${
objects.at(-1)?.id
}&limit=${limit}>; rel="prev"`
);
}
// Constuct HTTP Link header (next and prev)
const linkHeader = [];
if (objects.length > 0) {
const urlWithoutQuery = req.url.split("?")[0];
linkHeader.push(
`<${urlWithoutQuery}?max_id=${objects[0].id}&limit=${limit}>; rel="next"`,
);
linkHeader.push(
`<${urlWithoutQuery}?since_id=${
objects.at(-1)?.id
}&limit=${limit}>; rel="prev"`,
);
}
return jsonResponse(
await Promise.all(objects.map(n => notificationToAPI(n))),
200,
{
Link: linkHeader.join(", "),
}
);
return jsonResponse(
await Promise.all(objects.map((n) => notificationToAPI(n))),
200,
{
Link: linkHeader.join(", "),
},
);
});

Some files were not shown because too many files have changed in this diff Show more