mirror of
https://github.com/versia-pub/server.git
synced 2025-12-06 08:28:19 +01:00
refactor(api): ♻️ Move to Hono for HTTP
This commit is contained in:
parent
2237be3689
commit
826a260e90
|
|
@ -109,6 +109,15 @@ export const getFromRequest = async (req: Request): Promise<AuthData> => {
|
|||
return { user, token, application };
|
||||
};
|
||||
|
||||
export const getFromHeader = async (value: string): Promise<AuthData> => {
|
||||
const token = value.split(" ")[1];
|
||||
|
||||
const { user, application } =
|
||||
await retrieveUserAndApplicationFromToken(token);
|
||||
|
||||
return { user, token, application };
|
||||
};
|
||||
|
||||
export const followRequestUser = async (
|
||||
follower: User,
|
||||
followee: User,
|
||||
|
|
|
|||
43
index.ts
43
index.ts
|
|
@ -1,11 +1,13 @@
|
|||
import { dualLogger } from "@loggers";
|
||||
import { connectMeili } from "@meilisearch";
|
||||
import { config } from "config-manager";
|
||||
import { count } from "drizzle-orm";
|
||||
import { Hono } from "hono";
|
||||
import { LogLevel, LogManager, type MultiLogManager } from "log-manager";
|
||||
import { db, setupDatabase } from "~drizzle/db";
|
||||
import { Notes } from "~drizzle/schema";
|
||||
import { createServer } from "~server";
|
||||
import { setupDatabase } from "~drizzle/db";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
import type { APIRouteExports } from "~packages/server-handler";
|
||||
import { routes } from "~routes";
|
||||
import { createServer } from "~server2";
|
||||
|
||||
const timeAtStart = performance.now();
|
||||
|
||||
|
|
@ -28,20 +30,7 @@ if (config.meilisearch.enabled) {
|
|||
}
|
||||
|
||||
// Check if database is reachable
|
||||
let postCount = 0;
|
||||
try {
|
||||
postCount = (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Notes)
|
||||
)[0].count;
|
||||
} catch (e) {
|
||||
const error = e as Error;
|
||||
await dualServerLogger.logError(LogLevel.CRITICAL, "Database", error);
|
||||
process.exit(1);
|
||||
}
|
||||
const postCount = await Note.getCount();
|
||||
|
||||
if (isEntry) {
|
||||
// Check if JWT private key is set in config
|
||||
|
|
@ -110,7 +99,21 @@ if (isEntry) {
|
|||
}
|
||||
}
|
||||
|
||||
const server = createServer(config, dualServerLogger, true);
|
||||
const app = new Hono();
|
||||
|
||||
// Inject own filesystem router
|
||||
for (const [route, path] of Object.entries(routes)) {
|
||||
// use app.get(path, handler) to add routes
|
||||
const route: APIRouteExports = await import(path);
|
||||
|
||||
if (!route.meta || !route.default) {
|
||||
throw new Error(`Route ${path} does not have the correct exports.`);
|
||||
}
|
||||
|
||||
route.default(app);
|
||||
}
|
||||
|
||||
createServer(config, app);
|
||||
|
||||
await dualServerLogger.log(
|
||||
LogLevel.INFO,
|
||||
|
|
@ -161,4 +164,4 @@ if (config.frontend.enabled) {
|
|||
);
|
||||
}
|
||||
|
||||
export { config, server };
|
||||
export { app };
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@
|
|||
},
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "bun run --watch index.ts",
|
||||
"dev": "bun run --hot index.ts",
|
||||
"start": "NODE_ENV=production bun run dist/index.js --prod",
|
||||
"lint": "bunx @biomejs/biome check .",
|
||||
"prod-build": "bun run build.ts",
|
||||
|
|
@ -80,6 +80,7 @@
|
|||
"config-manager": "workspace:*",
|
||||
"drizzle-orm": "^0.30.7",
|
||||
"extract-zip": "^2.0.1",
|
||||
"hono": "^4.3.2",
|
||||
"html-to-text": "^9.0.5",
|
||||
"ioredis": "^5.3.2",
|
||||
"ip-matching": "^2.1.2",
|
||||
|
|
@ -99,6 +100,7 @@
|
|||
"mime-types": "^2.1.35",
|
||||
"oauth4webapi": "^2.4.0",
|
||||
"pg": "^8.11.5",
|
||||
"qs": "^6.12.1",
|
||||
"request-parser": "workspace:*",
|
||||
"sharp": "^0.33.3",
|
||||
"string-comparison": "^1.3.0",
|
||||
|
|
|
|||
|
|
@ -3,10 +3,12 @@ import {
|
|||
type InferInsertModel,
|
||||
type SQL,
|
||||
and,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
inArray,
|
||||
isNotNull,
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
import { htmlToText } from "html-to-text";
|
||||
import type * as Lysand from "lysand-types";
|
||||
|
|
@ -161,6 +163,19 @@ export class Note {
|
|||
return new User(this.status.author);
|
||||
}
|
||||
|
||||
static async getCount() {
|
||||
return (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Notes)
|
||||
.where(
|
||||
sql`EXISTS (SELECT 1 FROM "Users" WHERE "Users"."id" = ${Notes.authorId} AND "Users"."instanceId" IS NULL)`,
|
||||
)
|
||||
)[0].count;
|
||||
}
|
||||
|
||||
async getReplyChildren() {
|
||||
return await Note.manyFromSql(eq(Notes.replyId, this.status.id));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,17 @@ import { idValidator } from "@api";
|
|||
import { getBestContentType, urlToContentFormat } from "@content_types";
|
||||
import { addUserToMeilisearch } from "@meilisearch";
|
||||
import { proxyUrl } from "@response";
|
||||
import { type SQL, and, desc, eq, inArray } from "drizzle-orm";
|
||||
import {
|
||||
type SQL,
|
||||
and,
|
||||
count,
|
||||
countDistinct,
|
||||
desc,
|
||||
eq,
|
||||
gte,
|
||||
inArray,
|
||||
isNull,
|
||||
} from "drizzle-orm";
|
||||
import { htmlToText } from "html-to-text";
|
||||
import type * as Lysand from "lysand-types";
|
||||
import {
|
||||
|
|
@ -20,6 +30,7 @@ import { db } from "~drizzle/db";
|
|||
import {
|
||||
EmojiToUser,
|
||||
NoteToMentions,
|
||||
Notes,
|
||||
UserToPinnedNotes,
|
||||
Users,
|
||||
} from "~drizzle/schema";
|
||||
|
|
@ -102,6 +113,37 @@ export class User {
|
|||
return uri || new URL(`/users/${id}`, baseUrl).toString();
|
||||
}
|
||||
|
||||
static async getCount() {
|
||||
return (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Users)
|
||||
.where(isNull(Users.instanceId))
|
||||
)[0].count;
|
||||
}
|
||||
|
||||
static async getActiveInPeriod(milliseconds: number) {
|
||||
return (
|
||||
await db
|
||||
.select({
|
||||
count: countDistinct(Users),
|
||||
})
|
||||
.from(Users)
|
||||
.leftJoin(Notes, eq(Users.id, Notes.authorId))
|
||||
.where(
|
||||
and(
|
||||
isNull(Users.instanceId),
|
||||
gte(
|
||||
Notes.createdAt,
|
||||
new Date(Date.now() - milliseconds).toISOString(),
|
||||
),
|
||||
),
|
||||
)
|
||||
)[0].count;
|
||||
}
|
||||
|
||||
async pin(note: Note) {
|
||||
return (
|
||||
await db
|
||||
|
|
|
|||
|
|
@ -260,3 +260,23 @@ export const signedFetch = async (
|
|||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Export all schemas as a single object
|
||||
export default {
|
||||
Note: schemas.Note,
|
||||
User: schemas.User,
|
||||
Reaction: schemas.Reaction,
|
||||
Poll: schemas.Poll,
|
||||
Vote: schemas.Vote,
|
||||
VoteResult: schemas.VoteResult,
|
||||
Report: schemas.Report,
|
||||
ServerMetadata: schemas.ServerMetadata,
|
||||
Like: schemas.Like,
|
||||
Dislike: schemas.Dislike,
|
||||
Follow: schemas.Follow,
|
||||
FollowAccept: schemas.FollowAccept,
|
||||
FollowReject: schemas.FollowReject,
|
||||
Announce: schemas.Announce,
|
||||
Undo: schemas.Undo,
|
||||
Entity: schemas.Entity,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import { dualLogger } from "@loggers";
|
|||
import { errorResponse, jsonResponse, response } from "@response";
|
||||
import type { MatchedRoute } from "bun";
|
||||
import { type Config, config } from "config-manager";
|
||||
import type { Hono } from "hono";
|
||||
import type { RouterRoute } from "hono/types";
|
||||
import { LogLevel, type LogManager, type MultiLogManager } from "log-manager";
|
||||
import { RequestParser } from "request-parser";
|
||||
import type { ZodType, z } from "zod";
|
||||
|
|
@ -11,7 +13,7 @@ import { type AuthData, getFromRequest } from "~database/entities/User";
|
|||
import type { User } from "~packages/database-interface/user";
|
||||
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
|
||||
export type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
|
||||
|
||||
export type RouteHandler<
|
||||
RouteMeta extends APIRouteMetadata,
|
||||
|
|
@ -54,8 +56,11 @@ export interface APIRouteMetadata {
|
|||
|
||||
export interface APIRouteExports {
|
||||
meta: APIRouteMetadata;
|
||||
schema: z.AnyZodObject;
|
||||
default: RouteHandler<APIRouteMetadata, z.AnyZodObject>;
|
||||
schemas?: {
|
||||
query?: z.AnyZodObject;
|
||||
body?: z.AnyZodObject;
|
||||
};
|
||||
default: (app: Hono) => RouterRoute;
|
||||
}
|
||||
|
||||
export const processRoute = async (
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ export const routeMatcher = new Bun.FileSystemRouter({
|
|||
});
|
||||
|
||||
// Transform routes to be relative to the server/api directory
|
||||
const routes = routeMatcher.routes;
|
||||
let routes = routeMatcher.routes;
|
||||
|
||||
for (const [route, path] of Object.entries(routes)) {
|
||||
routes[route] = path.replace(join(process.cwd()), ".");
|
||||
|
|
@ -17,6 +17,9 @@ for (const [route, path] of Object.entries(routes)) {
|
|||
}
|
||||
}
|
||||
|
||||
// Prevent catch-all routes from being first by reversinbg the order
|
||||
routes = Object.fromEntries(Object.entries(routes).reverse());
|
||||
|
||||
export { routes };
|
||||
|
||||
export const matchRoute = (request: Request) => {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig } from "@api";
|
||||
import { jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { config } from "~packages/config-manager";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
|
|
@ -13,17 +15,16 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const config = await extraData.configManager.getConfig();
|
||||
|
||||
return jsonResponse({
|
||||
http: {
|
||||
bind: config.http.bind,
|
||||
bind_port: config.http.bind_port,
|
||||
base_url: config.http.base_url,
|
||||
url: config.http.bind.includes("http")
|
||||
? `${config.http.bind}:${config.http.bind_port}`
|
||||
: `http://${config.http.bind}:${config.http.bind_port}`,
|
||||
},
|
||||
export default (app: Hono) =>
|
||||
app.on(meta.allowedMethods, meta.route, async (context) => {
|
||||
return jsonResponse({
|
||||
http: {
|
||||
bind: config.http.bind,
|
||||
bind_port: config.http.bind_port,
|
||||
base_url: config.http.base_url,
|
||||
url: config.http.bind.includes("http")
|
||||
? `${config.http.bind}:${config.http.bind_port}`
|
||||
: `http://${config.http.bind}:${config.http.bind_port}`,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, response } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { SignJWT } from "jose";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
|
|
@ -20,35 +22,39 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
email: z.string().email().toLowerCase(),
|
||||
password: z.string().min(2).max(100),
|
||||
scope: z.string().optional(),
|
||||
redirect_uri: z.string().url().optional(),
|
||||
response_type: z.enum([
|
||||
"code",
|
||||
"token",
|
||||
"none",
|
||||
"id_token",
|
||||
"code id_token",
|
||||
"code token",
|
||||
"token id_token",
|
||||
"code token id_token",
|
||||
]),
|
||||
client_id: z.string(),
|
||||
state: z.string().optional(),
|
||||
code_challenge: z.string().optional(),
|
||||
code_challenge_method: z.enum(["plain", "S256"]).optional(),
|
||||
prompt: z
|
||||
.enum(["none", "login", "consent", "select_account"])
|
||||
.optional()
|
||||
.default("none"),
|
||||
max_age: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.default(60 * 60 * 24 * 7),
|
||||
});
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
email: z.string().email().toLowerCase(),
|
||||
password: z.string().min(2).max(100),
|
||||
}),
|
||||
query: z.object({
|
||||
scope: z.string().optional(),
|
||||
redirect_uri: z.string().url().optional(),
|
||||
response_type: z.enum([
|
||||
"code",
|
||||
"token",
|
||||
"none",
|
||||
"id_token",
|
||||
"code id_token",
|
||||
"code token",
|
||||
"token id_token",
|
||||
"code token id_token",
|
||||
]),
|
||||
client_id: z.string(),
|
||||
state: z.string().optional(),
|
||||
code_challenge: z.string().optional(),
|
||||
code_challenge_method: z.enum(["plain", "S256"]).optional(),
|
||||
prompt: z
|
||||
.enum(["none", "login", "consent", "select_account"])
|
||||
.optional()
|
||||
.default("none"),
|
||||
max_age: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.default(60 * 60 * 24 * 7),
|
||||
}),
|
||||
};
|
||||
|
||||
const returnError = (query: object, error: string, description: string) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
|
|
@ -66,91 +72,92 @@ const returnError = (query: object, error: string, description: string) => {
|
|||
Location: `/oauth/authorize?${searchParams.toString()}`,
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Login flow
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { email, password } = extraData.parsedRequest;
|
||||
|
||||
if (!email || !password)
|
||||
return returnError(
|
||||
extraData.parsedRequest,
|
||||
"invalid_request",
|
||||
"Missing email or password",
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
async (context) => {
|
||||
const { email, password } = context.req.valid("form");
|
||||
const { client_id } = context.req.valid("query");
|
||||
|
||||
// Find user
|
||||
const user = await User.fromSql(
|
||||
eq(Users.email, email.toLowerCase()),
|
||||
);
|
||||
|
||||
// Find user
|
||||
const user = await User.fromSql(eq(Users.email, email.toLowerCase()));
|
||||
if (
|
||||
!user ||
|
||||
!(await Bun.password.verify(
|
||||
password,
|
||||
user.getUser().password || "",
|
||||
))
|
||||
)
|
||||
return returnError(
|
||||
context.req.query(),
|
||||
"invalid_request",
|
||||
"Invalid email or password",
|
||||
);
|
||||
|
||||
if (
|
||||
!user ||
|
||||
!(await Bun.password.verify(
|
||||
password,
|
||||
user.getUser().password || "",
|
||||
))
|
||||
)
|
||||
return returnError(
|
||||
extraData.parsedRequest,
|
||||
"invalid_request",
|
||||
"Invalid email or password",
|
||||
// Try and import the key
|
||||
const privateKey = await crypto.subtle.importKey(
|
||||
"pkcs8",
|
||||
Buffer.from(config.oidc.jwt_key.split(";")[0], "base64"),
|
||||
"Ed25519",
|
||||
false,
|
||||
["sign"],
|
||||
);
|
||||
|
||||
const { client_id } = extraData.parsedRequest;
|
||||
// Generate JWT
|
||||
const jwt = await new SignJWT({
|
||||
sub: user.id,
|
||||
iss: new URL(config.http.base_url).origin,
|
||||
aud: client_id,
|
||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||
iat: Math.floor(Date.now() / 1000),
|
||||
nbf: Math.floor(Date.now() / 1000),
|
||||
})
|
||||
.setProtectedHeader({ alg: "EdDSA" })
|
||||
.sign(privateKey);
|
||||
|
||||
// Try and import the key
|
||||
const privateKey = await crypto.subtle.importKey(
|
||||
"pkcs8",
|
||||
Buffer.from(config.oidc.jwt_key.split(";")[0], "base64"),
|
||||
"Ed25519",
|
||||
false,
|
||||
["sign"],
|
||||
);
|
||||
const application = await db.query.Applications.findFirst({
|
||||
where: (app, { eq }) => eq(app.clientId, client_id),
|
||||
});
|
||||
|
||||
// Generate JWT
|
||||
const jwt = await new SignJWT({
|
||||
sub: user.id,
|
||||
iss: new URL(config.http.base_url).origin,
|
||||
aud: client_id,
|
||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||
iat: Math.floor(Date.now() / 1000),
|
||||
nbf: Math.floor(Date.now() / 1000),
|
||||
})
|
||||
.setProtectedHeader({ alg: "EdDSA" })
|
||||
.sign(privateKey);
|
||||
if (!application) {
|
||||
return errorResponse("Invalid application", 400);
|
||||
}
|
||||
|
||||
const application = await db.query.Applications.findFirst({
|
||||
where: (app, { eq }) => eq(app.clientId, client_id),
|
||||
});
|
||||
const searchParams = new URLSearchParams({
|
||||
application: application.name,
|
||||
client_secret: application.secret,
|
||||
});
|
||||
|
||||
if (!application) {
|
||||
return errorResponse("Invalid application", 400);
|
||||
}
|
||||
if (application.website)
|
||||
searchParams.append("website", application.website);
|
||||
|
||||
const searchParams = new URLSearchParams({
|
||||
application: application.name,
|
||||
client_secret: application.secret,
|
||||
});
|
||||
// Add all data that is not undefined except email and password
|
||||
for (const [key, value] of Object.entries(context.req.query())) {
|
||||
if (
|
||||
key !== "email" &&
|
||||
key !== "password" &&
|
||||
value !== undefined
|
||||
)
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
|
||||
if (application.website)
|
||||
searchParams.append("website", application.website);
|
||||
|
||||
// Add all data that is not undefined except email and password
|
||||
for (const [key, value] of Object.entries(extraData.parsedRequest)) {
|
||||
if (key !== "email" && key !== "password" && value !== undefined)
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
|
||||
// Redirect to OAuth authorize with JWT
|
||||
return response(null, 302, {
|
||||
Location: new URL(
|
||||
`/oauth/consent?${searchParams.toString()}`,
|
||||
config.http.base_url,
|
||||
).toString(),
|
||||
// Set cookie with JWT
|
||||
"Set-Cookie": `jwt=${jwt}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${
|
||||
60 * 60
|
||||
}`,
|
||||
});
|
||||
},
|
||||
);
|
||||
// Redirect to OAuth authorize with JWT
|
||||
return response(null, 302, {
|
||||
Location: new URL(
|
||||
`/oauth/consent?${searchParams.toString()}`,
|
||||
config.http.base_url,
|
||||
).toString(),
|
||||
// Set cookie with JWT
|
||||
"Set-Cookie": `jwt=${jwt}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${
|
||||
60 * 60
|
||||
}`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { randomBytes } from "node:crypto";
|
||||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { response } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { TokenType } from "~database/entities/Token";
|
||||
import { db } from "~drizzle/db";
|
||||
|
|
@ -20,66 +23,68 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
user: z.object({
|
||||
email: z.string().email().toLowerCase(),
|
||||
password: z.string().max(100).min(3),
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
user: z.object({
|
||||
email: z.string().email().toLowerCase(),
|
||||
password: z.string().min(2).max(100),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Mastodon-FE login route
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const {
|
||||
user: { email, password },
|
||||
} = extraData.parsedRequest;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
async (context) => {
|
||||
const {
|
||||
user: { email, password },
|
||||
} = context.req.valid("form");
|
||||
|
||||
const redirectToLogin = (error: string) =>
|
||||
Response.redirect(
|
||||
`/auth/sign_in?${new URLSearchParams({
|
||||
...matchedRoute.query,
|
||||
error: encodeURIComponent(error),
|
||||
}).toString()}`,
|
||||
302,
|
||||
);
|
||||
const redirectToLogin = (error: string) =>
|
||||
response(null, 302, {
|
||||
Location: `/auth/sign_in?${new URLSearchParams({
|
||||
...context.req.query,
|
||||
error: encodeURIComponent(error),
|
||||
}).toString()}`,
|
||||
});
|
||||
|
||||
const user = await User.fromSql(eq(Users.email, email));
|
||||
const user = await User.fromSql(eq(Users.email, email));
|
||||
|
||||
if (
|
||||
!user ||
|
||||
!(await Bun.password.verify(
|
||||
password,
|
||||
user.getUser().password || "",
|
||||
))
|
||||
)
|
||||
return redirectToLogin("Invalid email or password");
|
||||
if (
|
||||
!user ||
|
||||
!(await Bun.password.verify(
|
||||
password,
|
||||
user.getUser().password || "",
|
||||
))
|
||||
)
|
||||
return redirectToLogin("Invalid email or password");
|
||||
|
||||
const code = randomBytes(32).toString("hex");
|
||||
const accessToken = randomBytes(64).toString("base64url");
|
||||
const code = randomBytes(32).toString("hex");
|
||||
const accessToken = randomBytes(64).toString("base64url");
|
||||
|
||||
await db.insert(Tokens).values({
|
||||
accessToken,
|
||||
code: code,
|
||||
scope: "read write follow push",
|
||||
tokenType: TokenType.BEARER,
|
||||
applicationId: null,
|
||||
userId: user.id,
|
||||
});
|
||||
await db.insert(Tokens).values({
|
||||
accessToken,
|
||||
code: code,
|
||||
scope: "read write follow push",
|
||||
tokenType: TokenType.BEARER,
|
||||
applicationId: null,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
// One week from now
|
||||
const maxAge = String(60 * 60 * 24 * 7);
|
||||
// One week from now
|
||||
const maxAge = String(60 * 60 * 24 * 7);
|
||||
|
||||
// Redirect to home
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
// Redirect to home
|
||||
return response(null, 303, {
|
||||
Location: "/",
|
||||
"Set-Cookie": `_session_id=${accessToken}; Domain=${
|
||||
new URL(config.http.base_url).hostname
|
||||
}; SameSite=Lax; Path=/; HttpOnly; Max-Age=${maxAge}`,
|
||||
},
|
||||
status: 303,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig } from "@api";
|
||||
import type { Hono } from "hono";
|
||||
import { config } from "~packages/config-manager";
|
||||
|
||||
export const meta = applyConfig({
|
||||
|
|
@ -16,15 +17,15 @@ export const meta = applyConfig({
|
|||
/**
|
||||
* Mastodon-FE logout route
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
// Redirect to home
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
Location: "/",
|
||||
"Set-Cookie": `_session_id=; Domain=${
|
||||
new URL(config.http.base_url).hostname
|
||||
}; SameSite=Lax; Path=/; HttpOnly; Max-Age=0; Expires=${new Date().toUTCString()}`,
|
||||
},
|
||||
status: 303,
|
||||
export default (app: Hono) =>
|
||||
app.on(meta.allowedMethods, meta.route, async () => {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
Location: "/",
|
||||
"Set-Cookie": `_session_id=; Domain=${
|
||||
new URL(config.http.base_url).hostname
|
||||
}; SameSite=Lax; Path=/; HttpOnly; Max-Age=0; Expires=${new Date().toUTCString()}`,
|
||||
},
|
||||
status: 303,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Applications, Tokens } from "~drizzle/schema";
|
||||
|
||||
|
|
@ -15,33 +18,54 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
redirect_uri: z.string().url(),
|
||||
client_id: z.string(),
|
||||
code: z.string(),
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* OAuth Code flow
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute) => {
|
||||
const redirect_uri = decodeURIComponent(matchedRoute.query.redirect_uri);
|
||||
const client_id = matchedRoute.query.client_id;
|
||||
const code = matchedRoute.query.code;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
async (context) => {
|
||||
const { redirect_uri, client_id, code } =
|
||||
context.req.valid("query");
|
||||
|
||||
const redirectToLogin = (error: string) =>
|
||||
Response.redirect(
|
||||
`/oauth/authorize?${new URLSearchParams({
|
||||
...matchedRoute.query,
|
||||
error: encodeURIComponent(error),
|
||||
}).toString()}`,
|
||||
302,
|
||||
);
|
||||
const redirectToLogin = (error: string) =>
|
||||
Response.redirect(
|
||||
`/oauth/authorize?${new URLSearchParams({
|
||||
...context.req.query,
|
||||
error: encodeURIComponent(error),
|
||||
}).toString()}`,
|
||||
302,
|
||||
);
|
||||
|
||||
const foundToken = await db
|
||||
.select()
|
||||
.from(Tokens)
|
||||
.leftJoin(Applications, eq(Tokens.applicationId, Applications.id))
|
||||
.where(and(eq(Tokens.code, code), eq(Applications.clientId, client_id)))
|
||||
.limit(1);
|
||||
const foundToken = await db
|
||||
.select()
|
||||
.from(Tokens)
|
||||
.leftJoin(
|
||||
Applications,
|
||||
eq(Tokens.applicationId, Applications.id),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(Tokens.code, code),
|
||||
eq(Applications.clientId, client_id),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!foundToken || foundToken.length <= 0)
|
||||
return redirectToLogin("Invalid code");
|
||||
if (!foundToken || foundToken.length <= 0)
|
||||
return redirectToLogin("Invalid code");
|
||||
|
||||
// Redirect back to application
|
||||
return Response.redirect(`${redirect_uri}?code=${code}`, 302);
|
||||
});
|
||||
// Redirect back to application
|
||||
return Response.redirect(`${redirect_uri}?code=${code}`, 302);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
66
server/api/api/v1/accounts/:id/block.ts
Normal file
66
server/api/api/v1/accounts/:id/block.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/block",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:blocks"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (!foundRelationship.blocking) {
|
||||
foundRelationship.blocking = true;
|
||||
}
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
blocking: true,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -27,6 +27,10 @@ describe(meta.route, () => {
|
|||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
@ -47,7 +51,9 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
@ -65,7 +71,9 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
@ -86,7 +94,9 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
79
server/api/api/v1/accounts/:id/follow.ts
Normal file
79
server/api/api/v1/accounts/:id/follow.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import ISO6391 from "iso-639-1";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import {
|
||||
followRequestUser,
|
||||
getRelationshipToOtherUser,
|
||||
} from "~database/entities/User";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/follow",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:follows"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
json: z
|
||||
.object({
|
||||
reblogs: z.coerce.boolean().optional(),
|
||||
notify: z.coerce.boolean().optional(),
|
||||
languages: z
|
||||
.array(z.enum(ISO6391.getAllCodes() as [string, ...string[]]))
|
||||
.optional(),
|
||||
})
|
||||
.optional()
|
||||
.default({ reblogs: true, notify: false, languages: [] }),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
zValidator("json", schemas.json, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
const { reblogs, notify, languages } = context.req.valid("json");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
let relationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (!relationship.following) {
|
||||
relationship = await followRequestUser(
|
||||
user,
|
||||
otherUser,
|
||||
relationship.id,
|
||||
reblogs,
|
||||
notify,
|
||||
languages,
|
||||
);
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(relationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -28,7 +28,9 @@ beforeAll(async () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
74
server/api/api/v1/accounts/:id/followers.ts
Normal file
74
server/api/api/v1/accounts/:id/followers.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 60,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/followers",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: ["read:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(40).optional().default(20),
|
||||
}),
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
const { max_id, since_id, min_id, limit } =
|
||||
context.req.valid("query");
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
// TODO: Add follower/following privacy settings
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const { objects, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${otherUser.id} AND "Relationships"."ownerId" = ${Users.id} AND "Relationships"."following" = true)`,
|
||||
),
|
||||
limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((object) => object.toAPI())),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
@ -28,7 +28,9 @@ beforeAll(async () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
73
server/api/api/v1/accounts/:id/following.ts
Normal file
73
server/api/api/v1/accounts/:id/following.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 60,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/following",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: ["read:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(40).optional().default(20),
|
||||
}),
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
const { max_id, since_id, min_id } = context.req.valid("query");
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
// TODO: Add follower/following privacy settings
|
||||
|
||||
const { objects, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${otherUser.id} AND "Relationships"."following" = true)`,
|
||||
),
|
||||
context.req.valid("query").limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((object) => object.toAPI())),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
@ -20,17 +20,21 @@ afterAll(async () => {
|
|||
|
||||
beforeAll(async () => {
|
||||
for (const status of timeline) {
|
||||
await fetch(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/favourite`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/favourite`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
@ -46,7 +50,7 @@ describe(meta.route, () => {
|
|||
),
|
||||
),
|
||||
);
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.status).toBe(422);
|
||||
});
|
||||
|
||||
test("should return user", async () => {
|
||||
43
server/api/api/v1/accounts/:id/index.ts
Normal file
43
server/api/api/v1/accounts/:id/index.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { apiRoute, applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: [],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
const foundUser = await User.fromId(id);
|
||||
|
||||
if (!foundUser) return errorResponse("User not found", 404);
|
||||
|
||||
return jsonResponse(foundUser.toAPI(user?.id === foundUser.id));
|
||||
},
|
||||
);
|
||||
|
|
@ -27,6 +27,10 @@ describe(meta.route, () => {
|
|||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
@ -47,7 +51,9 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
@ -65,7 +71,9 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
@ -86,7 +94,9 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
83
server/api/api/v1/accounts/:id/mute.ts
Normal file
83
server/api/api/v1/accounts/:id/mute.ts
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/mute",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:mutes"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
json: z.object({
|
||||
notifications: z.boolean().optional(),
|
||||
duration: z
|
||||
.number()
|
||||
.int()
|
||||
.min(60)
|
||||
.max(60 * 60 * 24 * 365 * 5)
|
||||
.optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
zValidator("json", schemas.json, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
const { notifications, duration } = context.req.valid("json");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (!foundRelationship.muting) {
|
||||
foundRelationship.muting = true;
|
||||
}
|
||||
if (notifications ?? true) {
|
||||
foundRelationship.mutingNotifications = true;
|
||||
}
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
muting: true,
|
||||
mutingNotifications: notifications ?? true,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
// TODO: Implement duration
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
69
server/api/api/v1/accounts/:id/note.ts
Normal file
69
server/api/api/v1/accounts/:id/note.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/note",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
json: z.object({
|
||||
comment: z.string().min(0).max(5000).trim().optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
zValidator("json", schemas.json, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
const { comment } = context.req.valid("json");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
foundRelationship.note = comment ?? "";
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
note: foundRelationship.note,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
66
server/api/api/v1/accounts/:id/pin.ts
Normal file
66
server/api/api/v1/accounts/:id/pin.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/pin",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (!foundRelationship.endorsed) {
|
||||
foundRelationship.endorsed = true;
|
||||
}
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
endorsed: true,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
80
server/api/api/v1/accounts/:id/remove_from_followers.ts
Normal file
80
server/api/api/v1/accounts/:id/remove_from_followers.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import { apiRoute, applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/remove_from_followers",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:follows"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
self,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (foundRelationship.followedBy) {
|
||||
foundRelationship.followedBy = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
followedBy: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
if (otherUser.isLocal()) {
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
following: false,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.ownerId, otherUser.id),
|
||||
eq(Relationships.subjectId, self.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -1,13 +1,11 @@
|
|||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
||||
import { config } from "config-manager";
|
||||
import { db } from "~drizzle/db";
|
||||
import {
|
||||
deleteOldTestUsers,
|
||||
getTestStatuses,
|
||||
getTestUsers,
|
||||
sendTestRequest,
|
||||
} from "~tests/utils";
|
||||
import type { Account as APIAccount } from "~types/mastodon/account";
|
||||
import type { Status as APIStatus } from "~types/mastodon/status";
|
||||
import { meta } from "./statuses";
|
||||
|
||||
|
|
@ -21,6 +19,12 @@ afterAll(async () => {
|
|||
await deleteUsers();
|
||||
});
|
||||
|
||||
const getFormData = (object: Record<string, string | number | boolean>) =>
|
||||
Object.keys(object).reduce((formData, key) => {
|
||||
formData.append(key, String(object[key]));
|
||||
return formData;
|
||||
}, new FormData());
|
||||
|
||||
beforeAll(async () => {
|
||||
const response = await sendTestRequest(
|
||||
new Request(
|
||||
|
|
@ -100,9 +104,8 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
body: getFormData({
|
||||
status: "Reply",
|
||||
in_reply_to_id: timeline[0].id,
|
||||
federate: false,
|
||||
108
server/api/api/v1/accounts/:id/statuses.ts
Normal file
108
server/api/api/v1/accounts/:id/statuses.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq, gt, gte, isNull, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Notes } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/statuses",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: ["read:statuses"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.number().int().min(1).max(40).optional().default(20),
|
||||
only_media: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
exclude_replies: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
exclude_reblogs: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
pinned: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
tagged: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const {
|
||||
max_id,
|
||||
min_id,
|
||||
since_id,
|
||||
limit,
|
||||
exclude_reblogs,
|
||||
only_media,
|
||||
exclude_replies,
|
||||
pinned,
|
||||
} = context.req.valid("query");
|
||||
|
||||
const { objects, link } = await Timeline.getNoteTimeline(
|
||||
and(
|
||||
max_id ? lt(Notes.id, max_id) : undefined,
|
||||
since_id ? gte(Notes.id, since_id) : undefined,
|
||||
min_id ? gt(Notes.id, min_id) : undefined,
|
||||
eq(Notes.authorId, id),
|
||||
only_media
|
||||
? sql`EXISTS (SELECT 1 FROM "Attachments" WHERE "Attachments"."noteId" = ${Notes.id})`
|
||||
: undefined,
|
||||
pinned
|
||||
? sql`EXISTS (SELECT 1 FROM "UserToPinnedNotes" WHERE "UserToPinnedNotes"."noteId" = ${Notes.id} AND "UserToPinnedNotes"."userId" = ${otherUser.id})`
|
||||
: undefined,
|
||||
exclude_reblogs ? isNull(Notes.reblogId) : undefined,
|
||||
exclude_replies ? isNull(Notes.replyId) : undefined,
|
||||
),
|
||||
limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((note) => note.toAPI(otherUser))),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
66
server/api/api/v1/accounts/:id/unblock.ts
Normal file
66
server/api/api/v1/accounts/:id/unblock.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unblock",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:blocks"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (foundRelationship.blocking) {
|
||||
foundRelationship.blocking = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
blocking: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
67
server/api/api/v1/accounts/:id/unfollow.ts
Normal file
67
server/api/api/v1/accounts/:id/unfollow.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unfollow",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:follows"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
self,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (foundRelationship.following) {
|
||||
foundRelationship.following = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
following: false,
|
||||
requested: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
68
server/api/api/v1/accounts/:id/unmute.ts
Normal file
68
server/api/api/v1/accounts/:id/unmute.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unmute",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:mutes"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const user = await User.fromId(id);
|
||||
|
||||
if (!user) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
self,
|
||||
user,
|
||||
);
|
||||
|
||||
if (foundRelationship.muting) {
|
||||
foundRelationship.muting = false;
|
||||
foundRelationship.mutingNotifications = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
muting: false,
|
||||
mutingNotifications: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
66
server/api/api/v1/accounts/:id/unpin.ts
Normal file
66
server/api/api/v1/accounts/:id/unpin.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unpin",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
self,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
if (foundRelationship.endorsed) {
|
||||
foundRelationship.endorsed = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
endorsed: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/block",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:blocks"],
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Blocks a user
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, otherUser);
|
||||
|
||||
if (!foundRelationship.blocking) {
|
||||
foundRelationship.blocking = true;
|
||||
}
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
blocking: true,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,69 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import ISO6391 from "iso-639-1";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import {
|
||||
followRequestUser,
|
||||
getRelationshipToOtherUser,
|
||||
} from "~database/entities/User";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/follow",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:follows"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
reblogs: z.coerce.boolean().optional(),
|
||||
notify: z.coerce.boolean().optional(),
|
||||
languages: z
|
||||
.array(z.enum(ISO6391.getAllCodes() as [string, ...string[]]))
|
||||
.optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Follow a user
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { languages, notify, reblogs } = extraData.parsedRequest;
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
let relationship = await getRelationshipToOtherUser(self, otherUser);
|
||||
|
||||
if (!relationship.following) {
|
||||
relationship = await followRequestUser(
|
||||
self,
|
||||
otherUser,
|
||||
relationship.id,
|
||||
reblogs,
|
||||
notify,
|
||||
languages,
|
||||
);
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(relationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 60,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/followers",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: ["read:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(40).optional().default(20),
|
||||
});
|
||||
|
||||
/**
|
||||
* Fetch all statuses for a user
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { max_id, min_id, since_id, limit } = extraData.parsedRequest;
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const { objects, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${otherUser.id} AND "Relationships"."ownerId" = ${Users.id} AND "Relationships"."following" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((object) => object.toAPI())),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 60,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/following",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: ["read:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(40).optional().default(20),
|
||||
});
|
||||
|
||||
/**
|
||||
* Fetch all statuses for a user
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { max_id, min_id, since_id, limit } = extraData.parsedRequest;
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const { objects, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${otherUser.id} AND "Relationships"."following" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((object) => object.toAPI())),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: [],
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Fetch a user
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user } = extraData.auth;
|
||||
|
||||
const foundUser = await User.fromId(id);
|
||||
|
||||
if (!foundUser) return errorResponse("User not found", 404);
|
||||
|
||||
return jsonResponse(foundUser.toAPI(user?.id === foundUser.id));
|
||||
});
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/mute",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:mutes"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
notifications: z.coerce.boolean().optional(),
|
||||
duration: z
|
||||
.number()
|
||||
.int()
|
||||
.min(60)
|
||||
.max(60 * 60 * 24 * 365 * 5)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Mute a user
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { notifications, duration } = extraData.parsedRequest;
|
||||
|
||||
const user = await User.fromId(id);
|
||||
|
||||
if (!user) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, user);
|
||||
|
||||
if (!foundRelationship.muting) {
|
||||
foundRelationship.muting = true;
|
||||
}
|
||||
if (notifications ?? true) {
|
||||
foundRelationship.mutingNotifications = true;
|
||||
}
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
muting: true,
|
||||
mutingNotifications: notifications ?? true,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
// TODO: Implement duration
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/note",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
comment: z.string().min(0).max(5000).trim().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Sets a user note
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { comment } = extraData.parsedRequest;
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
self,
|
||||
otherUser,
|
||||
);
|
||||
|
||||
foundRelationship.note = comment ?? "";
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
note: foundRelationship.note,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/pin",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Pin a user
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, otherUser);
|
||||
|
||||
if (!foundRelationship.endorsed) {
|
||||
foundRelationship.endorsed = true;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
endorsed: true,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/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;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, otherUser);
|
||||
|
||||
if (foundRelationship.followedBy) {
|
||||
foundRelationship.followedBy = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
followedBy: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
|
||||
if (otherUser.isLocal()) {
|
||||
// Also remove from followers list
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
following: false,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.ownerId, otherUser.id),
|
||||
eq(Relationships.subjectId, self.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq, gt, gte, isNull, lt, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { Notes } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/statuses",
|
||||
auth: {
|
||||
required: false,
|
||||
oauthPermissions: ["read:statuses"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(40).optional().default(20),
|
||||
only_media: z.coerce.boolean().optional(),
|
||||
exclude_replies: z.coerce.boolean().optional(),
|
||||
exclude_reblogs: z.coerce.boolean().optional(),
|
||||
pinned: z.coerce.boolean().optional(),
|
||||
tagged: z.string().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Fetch all statuses for a user
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const {
|
||||
max_id,
|
||||
min_id,
|
||||
since_id,
|
||||
limit,
|
||||
exclude_reblogs,
|
||||
only_media,
|
||||
exclude_replies,
|
||||
pinned,
|
||||
} = extraData.parsedRequest;
|
||||
|
||||
const user = await User.fromId(id);
|
||||
|
||||
if (!user) return errorResponse("User not found", 404);
|
||||
|
||||
const { objects, link } = await Timeline.getNoteTimeline(
|
||||
and(
|
||||
max_id ? lt(Notes.id, max_id) : undefined,
|
||||
since_id ? gte(Notes.id, since_id) : undefined,
|
||||
min_id ? gt(Notes.id, min_id) : undefined,
|
||||
eq(Notes.authorId, id),
|
||||
only_media
|
||||
? sql`EXISTS (SELECT 1 FROM "Attachments" WHERE "Attachments"."noteId" = ${Notes.id})`
|
||||
: undefined,
|
||||
pinned
|
||||
? sql`EXISTS (SELECT 1 FROM "UserToPinnedNotes" WHERE "UserToPinnedNotes"."noteId" = ${Notes.id} AND "UserToPinnedNotes"."userId" = ${user.id})`
|
||||
: undefined,
|
||||
exclude_reblogs ? isNull(Notes.reblogId) : undefined,
|
||||
exclude_replies ? isNull(Notes.replyId) : undefined,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((note) => note.toAPI(user))),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unblock",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:blocks"],
|
||||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, otherUser);
|
||||
|
||||
if (foundRelationship.blocking) {
|
||||
foundRelationship.blocking = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
blocking: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unfollow",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:follows"],
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Unfollows a user
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, otherUser);
|
||||
|
||||
if (foundRelationship.following) {
|
||||
foundRelationship.following = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
following: false,
|
||||
requested: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unmute",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:mutes"],
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Unmute a user
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const user = await User.fromId(id);
|
||||
|
||||
if (!user) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, user);
|
||||
|
||||
if (foundRelationship.muting) {
|
||||
foundRelationship.muting = false;
|
||||
foundRelationship.mutingNotifications = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
muting: false,
|
||||
mutingNotifications: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { relationshipToAPI } from "~database/entities/Relationship";
|
||||
import { getRelationshipToOtherUser } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 30,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/accounts/:id/unpin",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:accounts"],
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Unpin a user
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const otherUser = await User.fromId(id);
|
||||
|
||||
if (!otherUser) return errorResponse("User not found", 404);
|
||||
|
||||
// Check if already following
|
||||
const foundRelationship = await getRelationshipToOtherUser(self, otherUser);
|
||||
|
||||
if (foundRelationship.endorsed) {
|
||||
foundRelationship.endorsed = false;
|
||||
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
endorsed: false,
|
||||
})
|
||||
.where(eq(Relationships.id, foundRelationship.id));
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { inArray } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Users } from "~drizzle/schema";
|
||||
|
|
@ -19,63 +21,69 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
id: z.array(z.string().regex(idValidator)).min(1).max(10),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
"id[]": z.array(z.string().uuid()).min(1).max(10),
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Find familiar followers (followers of a user that you also follow)
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user: self } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user: self } = context.req.valid("header");
|
||||
const { "id[]": ids } = context.req.valid("query");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { id: ids } = extraData.parsedRequest;
|
||||
const idFollowerRelationships =
|
||||
await db.query.Relationships.findMany({
|
||||
columns: {
|
||||
ownerId: true,
|
||||
},
|
||||
where: (relationship, { inArray, and, eq }) =>
|
||||
and(
|
||||
inArray(relationship.subjectId, ids),
|
||||
eq(relationship.following, true),
|
||||
),
|
||||
});
|
||||
|
||||
const idFollowerRelationships = await db.query.Relationships.findMany({
|
||||
columns: {
|
||||
ownerId: true,
|
||||
},
|
||||
where: (relationship, { inArray, and, eq }) =>
|
||||
and(
|
||||
inArray(relationship.subjectId, ids),
|
||||
eq(relationship.following, true),
|
||||
if (idFollowerRelationships.length === 0) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
|
||||
// Find users that you follow in idFollowerRelationships
|
||||
const relevantRelationships = await db.query.Relationships.findMany(
|
||||
{
|
||||
columns: {
|
||||
subjectId: true,
|
||||
},
|
||||
where: (relationship, { inArray, and, eq }) =>
|
||||
and(
|
||||
eq(relationship.ownerId, self.id),
|
||||
inArray(
|
||||
relationship.subjectId,
|
||||
idFollowerRelationships.map((f) => f.ownerId),
|
||||
),
|
||||
eq(relationship.following, true),
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
if (relevantRelationships.length === 0) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
|
||||
const finalUsers = await User.manyFromSql(
|
||||
inArray(
|
||||
Users.id,
|
||||
relevantRelationships.map((r) => r.subjectId),
|
||||
),
|
||||
});
|
||||
);
|
||||
|
||||
if (idFollowerRelationships.length === 0) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
|
||||
// Find users that you follow in idFollowerRelationships
|
||||
const relevantRelationships = await db.query.Relationships.findMany({
|
||||
columns: {
|
||||
subjectId: true,
|
||||
},
|
||||
where: (relationship, { inArray, and, eq }) =>
|
||||
and(
|
||||
eq(relationship.ownerId, self.id),
|
||||
inArray(
|
||||
relationship.subjectId,
|
||||
idFollowerRelationships.map((f) => f.ownerId),
|
||||
),
|
||||
eq(relationship.following, true),
|
||||
),
|
||||
});
|
||||
|
||||
if (relevantRelationships.length === 0) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
|
||||
const finalUsers = await User.manyFromSql(
|
||||
inArray(
|
||||
Users.id,
|
||||
relevantRelationships.map((r) => r.subjectId),
|
||||
),
|
||||
);
|
||||
|
||||
return jsonResponse(finalUsers.map((o) => o.toAPI()));
|
||||
},
|
||||
);
|
||||
return jsonResponse(finalUsers.map((o) => o.toAPI()));
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { apiRoute, applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { jsonResponse, response } from "@response";
|
||||
import { tempmailDomains } from "@tempmail";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import ISO6391 from "iso-639-1";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { config } from "~packages/config-manager";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
|
|
@ -20,210 +23,217 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
// No validation on the Zod side as we need to do custom validation
|
||||
export const schema = z.object({
|
||||
username: z.string().toLowerCase(),
|
||||
email: z.string().toLowerCase(),
|
||||
password: z.string(),
|
||||
agreement: z.boolean(),
|
||||
locale: z.string(),
|
||||
reason: z.string(),
|
||||
});
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
username: z.string(),
|
||||
email: z.string(),
|
||||
password: z.string(),
|
||||
agreement: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase())),
|
||||
locale: z.string(),
|
||||
reason: z.string(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
// TODO: Add Authorization check
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { username, email, password, agreement, locale, reason } =
|
||||
context.req.valid("form");
|
||||
|
||||
const body = extraData.parsedRequest;
|
||||
if (!config.signups.registration) {
|
||||
return jsonResponse(
|
||||
{
|
||||
error: "Registration is disabled",
|
||||
},
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const config = await extraData.configManager.getConfig();
|
||||
|
||||
if (!config.signups.registration) {
|
||||
return jsonResponse(
|
||||
{
|
||||
error: "Registration is disabled",
|
||||
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: [],
|
||||
},
|
||||
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: [],
|
||||
},
|
||||
};
|
||||
// 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 (!parsedRequest[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({
|
||||
// Check if username is valid
|
||||
if (!username?.match(/^[a-z0-9_]+$/))
|
||||
errors.details.username.push({
|
||||
error: "ERR_INVALID",
|
||||
description:
|
||||
"must only contain lowercase letters, numbers, and underscores",
|
||||
});
|
||||
|
||||
// Check if username doesnt match filters
|
||||
if (
|
||||
config.filters.username.some((filter) =>
|
||||
username?.match(filter),
|
||||
)
|
||||
) {
|
||||
errors.details.username.push({
|
||||
error: "ERR_INVALID",
|
||||
description: "contains blocked words",
|
||||
});
|
||||
}
|
||||
|
||||
// Check if username is too long
|
||||
if ((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 ((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(username ?? ""))
|
||||
errors.details.username.push({
|
||||
error: "ERR_RESERVED",
|
||||
description: "is reserved",
|
||||
});
|
||||
|
||||
// Check if username is taken
|
||||
if (await User.fromSql(eq(Users.username, username))) {
|
||||
errors.details.username.push({
|
||||
error: "ERR_TAKEN",
|
||||
description: "is already taken",
|
||||
});
|
||||
}
|
||||
|
||||
// Check if email is valid
|
||||
if (
|
||||
!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(email) ||
|
||||
(config.validation.blacklist_tempmail &&
|
||||
tempmailDomains.domains.includes(
|
||||
(email ?? "").split("@")[1],
|
||||
))
|
||||
)
|
||||
errors.details.email.push({
|
||||
error: "ERR_BLOCKED",
|
||||
description: "is from a blocked email provider",
|
||||
});
|
||||
|
||||
// Check if email is taken
|
||||
if (await User.fromSql(eq(Users.email, email)))
|
||||
errors.details.email.push({
|
||||
error: "ERR_TAKEN",
|
||||
description: "is already taken",
|
||||
});
|
||||
|
||||
// Check if agreement is accepted
|
||||
if (!agreement)
|
||||
errors.details.agreement.push({
|
||||
error: "ERR_ACCEPTED",
|
||||
description: "must be accepted",
|
||||
});
|
||||
|
||||
if (!locale)
|
||||
errors.details.locale.push({
|
||||
error: "ERR_BLANK",
|
||||
description: `can't be blank`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check if username is valid
|
||||
if (!body.username?.match(/^[a-z0-9_]+$/))
|
||||
errors.details.username.push({
|
||||
error: "ERR_INVALID",
|
||||
description:
|
||||
"must only contain lowercase letters, numbers, and underscores",
|
||||
});
|
||||
if (!ISO6391.validate(locale ?? ""))
|
||||
errors.details.locale.push({
|
||||
error: "ERR_INVALID",
|
||||
description: "must be a valid ISO 639-1 code",
|
||||
});
|
||||
|
||||
// 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",
|
||||
});
|
||||
}
|
||||
// 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"
|
||||
|
||||
// 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 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 User.fromSql(eq(Users.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 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 taken
|
||||
if (await User.fromSql(eq(Users.email, body.email)))
|
||||
errors.details.email.push({
|
||||
error: "ERR_TAKEN",
|
||||
description: "is already taken",
|
||||
});
|
||||
|
||||
// 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 (!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"
|
||||
|
||||
const errorsText = Object.entries(errors.details)
|
||||
.filter(([_, errors]) => errors.length > 0)
|
||||
.map(
|
||||
([name, errors]) =>
|
||||
`${name} ${errors
|
||||
.map((error) => error.description)
|
||||
.join(", ")}`,
|
||||
)
|
||||
.join(", ");
|
||||
return jsonResponse(
|
||||
{
|
||||
error: `Validation failed: ${errorsText}`,
|
||||
details: Object.fromEntries(
|
||||
Object.entries(errors.details).filter(
|
||||
([_, errors]) => errors.length > 0,
|
||||
const errorsText = Object.entries(errors.details)
|
||||
.filter(([_, errors]) => errors.length > 0)
|
||||
.map(
|
||||
([name, errors]) =>
|
||||
`${name} ${errors
|
||||
.map((error) => error.description)
|
||||
.join(", ")}`,
|
||||
)
|
||||
.join(", ");
|
||||
return jsonResponse(
|
||||
{
|
||||
error: `Validation failed: ${errorsText}`,
|
||||
details: Object.fromEntries(
|
||||
Object.entries(errors.details).filter(
|
||||
([_, errors]) => errors.length > 0,
|
||||
),
|
||||
),
|
||||
),
|
||||
},
|
||||
422,
|
||||
);
|
||||
}
|
||||
},
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
await User.fromDataLocal({
|
||||
username: body.username ?? "",
|
||||
password: body.password ?? "",
|
||||
email: body.email ?? "",
|
||||
});
|
||||
await User.fromDataLocal({
|
||||
username: username ?? "",
|
||||
password: password ?? "",
|
||||
email: email ?? "",
|
||||
});
|
||||
|
||||
return response(null, 200);
|
||||
},
|
||||
);
|
||||
return response(null, 200);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { dualLogger } from "@loggers";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import {
|
||||
anyOf,
|
||||
charIn,
|
||||
|
|
@ -32,73 +34,81 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
acct: z.string().min(1).max(512),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
acct: z.string().min(1).max(512),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { acct } = extraData.parsedRequest;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { acct } = context.req.valid("query");
|
||||
|
||||
if (!acct) {
|
||||
return errorResponse("Invalid acct parameter", 400);
|
||||
}
|
||||
|
||||
// Check if acct is matching format username@domain.com or @username@domain.com
|
||||
const accountMatches = acct?.trim().match(
|
||||
createRegExp(
|
||||
maybe("@"),
|
||||
oneOrMore(
|
||||
anyOf(letter.lowercase, digit, charIn("-")),
|
||||
).groupedAs("username"),
|
||||
exactly("@"),
|
||||
oneOrMore(anyOf(letter, digit, charIn("_-.:"))).groupedAs(
|
||||
"domain",
|
||||
),
|
||||
|
||||
[global],
|
||||
),
|
||||
);
|
||||
|
||||
if (accountMatches) {
|
||||
// Remove leading @ if it exists
|
||||
if (accountMatches[0].startsWith("@")) {
|
||||
accountMatches[0] = accountMatches[0].slice(1);
|
||||
if (!acct) {
|
||||
return errorResponse("Invalid acct parameter", 400);
|
||||
}
|
||||
|
||||
const [username, domain] = accountMatches[0].split("@");
|
||||
const foundAccount = await resolveWebFinger(username, domain).catch(
|
||||
(e) => {
|
||||
// Check if acct is matching format username@domain.com or @username@domain.com
|
||||
const accountMatches = acct?.trim().match(
|
||||
createRegExp(
|
||||
maybe("@"),
|
||||
oneOrMore(
|
||||
anyOf(letter.lowercase, digit, charIn("-")),
|
||||
).groupedAs("username"),
|
||||
exactly("@"),
|
||||
oneOrMore(anyOf(letter, digit, charIn("_-.:"))).groupedAs(
|
||||
"domain",
|
||||
),
|
||||
|
||||
[global],
|
||||
),
|
||||
);
|
||||
|
||||
if (accountMatches) {
|
||||
// Remove leading @ if it exists
|
||||
if (accountMatches[0].startsWith("@")) {
|
||||
accountMatches[0] = accountMatches[0].slice(1);
|
||||
}
|
||||
|
||||
const [username, domain] = accountMatches[0].split("@");
|
||||
const foundAccount = await resolveWebFinger(
|
||||
username,
|
||||
domain,
|
||||
).catch((e) => {
|
||||
dualLogger.logError(
|
||||
LogLevel.ERROR,
|
||||
"WebFinger.Resolve",
|
||||
e as Error,
|
||||
);
|
||||
return null;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if (foundAccount) {
|
||||
return jsonResponse(foundAccount.toAPI());
|
||||
if (foundAccount) {
|
||||
return jsonResponse(foundAccount.toAPI());
|
||||
}
|
||||
|
||||
return errorResponse("Account not found", 404);
|
||||
}
|
||||
|
||||
return errorResponse("Account not found", 404);
|
||||
}
|
||||
let username = acct;
|
||||
if (username.startsWith("@")) {
|
||||
username = username.slice(1);
|
||||
}
|
||||
|
||||
let username = acct;
|
||||
if (username.startsWith("@")) {
|
||||
username = username.slice(1);
|
||||
}
|
||||
const account = await User.fromSql(eq(Users.username, username));
|
||||
|
||||
const account = await User.fromSql(eq(Users.username, username));
|
||||
if (account) {
|
||||
return jsonResponse(account.toAPI());
|
||||
}
|
||||
|
||||
if (account) {
|
||||
return jsonResponse(account.toAPI());
|
||||
}
|
||||
|
||||
return errorResponse(
|
||||
`Account with username ${username} not found`,
|
||||
404,
|
||||
);
|
||||
},
|
||||
);
|
||||
return errorResponse(
|
||||
`Account with username ${username} not found`,
|
||||
404,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
createNewRelationship,
|
||||
relationshipToAPI,
|
||||
} from "~database/entities/Relationship";
|
||||
import type { UserType } from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
|
|
@ -21,48 +23,48 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
id: z.array(z.string().regex(idValidator)).min(1).max(10),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
"id[]": z.array(z.string().uuid()).min(1).max(10),
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Find relationships
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user: self } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user: self } = context.req.valid("header");
|
||||
const { "id[]": ids } = context.req.valid("query");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { id: ids } = extraData.parsedRequest;
|
||||
const relationships = await db.query.Relationships.findMany({
|
||||
where: (relationship, { inArray, and, eq }) =>
|
||||
and(
|
||||
inArray(relationship.subjectId, ids),
|
||||
eq(relationship.ownerId, self.id),
|
||||
),
|
||||
});
|
||||
|
||||
const relationships = await db.query.Relationships.findMany({
|
||||
where: (relationship, { inArray, and, eq }) =>
|
||||
and(
|
||||
inArray(relationship.subjectId, ids),
|
||||
eq(relationship.ownerId, self.id),
|
||||
),
|
||||
});
|
||||
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),
|
||||
);
|
||||
for (const id of missingIds) {
|
||||
const user = await User.fromId(id);
|
||||
if (!user) continue;
|
||||
const relationship = await createNewRelationship(self, user);
|
||||
|
||||
// Create the missing relationships
|
||||
for (const id of missingIds) {
|
||||
const relationship = await createNewRelationship(self, {
|
||||
id,
|
||||
} as UserType);
|
||||
relationships.push(relationship);
|
||||
}
|
||||
|
||||
relationships.push(relationship);
|
||||
}
|
||||
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)));
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq, like, not, or, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import {
|
||||
anyOf,
|
||||
charIn,
|
||||
|
|
@ -31,87 +33,90 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
q: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(512)
|
||||
.regex(
|
||||
createRegExp(
|
||||
maybe("@"),
|
||||
oneOrMore(
|
||||
anyOf(letter.lowercase, digit, charIn("-")),
|
||||
).groupedAs("username"),
|
||||
maybe(
|
||||
exactly("@"),
|
||||
oneOrMore(anyOf(letter, digit, charIn("_-.:"))).groupedAs(
|
||||
"domain",
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
q: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(512)
|
||||
.regex(
|
||||
createRegExp(
|
||||
maybe("@"),
|
||||
oneOrMore(
|
||||
anyOf(letter.lowercase, digit, charIn("-")),
|
||||
).groupedAs("username"),
|
||||
maybe(
|
||||
exactly("@"),
|
||||
oneOrMore(
|
||||
anyOf(letter, digit, charIn("_-.:")),
|
||||
).groupedAs("domain"),
|
||||
),
|
||||
[global],
|
||||
),
|
||||
[global],
|
||||
),
|
||||
),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
offset: z.coerce.number().int().optional(),
|
||||
resolve: z.coerce.boolean().optional(),
|
||||
following: z.coerce.boolean().optional(),
|
||||
});
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
offset: z.coerce.number().int().optional(),
|
||||
resolve: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
following: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
// TODO: Add checks for disabled or not email verified accounts
|
||||
const {
|
||||
following = false,
|
||||
limit,
|
||||
offset,
|
||||
resolve,
|
||||
q,
|
||||
} = extraData.parsedRequest;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { q, limit, offset, resolve, following } =
|
||||
context.req.valid("query");
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
const { user: self } = extraData.auth;
|
||||
if (!self && following) return errorResponse("Unauthorized", 401);
|
||||
|
||||
if (!self && following) return errorResponse("Unauthorized", 401);
|
||||
const [username, host] = q.replace(/^@/, "").split("@");
|
||||
|
||||
// Remove any leading @
|
||||
const [username, host] = q.replace(/^@/, "").split("@");
|
||||
const accounts: User[] = [];
|
||||
|
||||
const accounts: User[] = [];
|
||||
if (resolve && username && host) {
|
||||
const resolvedUser = await resolveWebFinger(username, host);
|
||||
|
||||
if (resolve && username && host) {
|
||||
const resolvedUser = await resolveWebFinger(username, host);
|
||||
|
||||
if (resolvedUser) {
|
||||
accounts.push(resolvedUser);
|
||||
if (resolvedUser) {
|
||||
accounts.push(resolvedUser);
|
||||
}
|
||||
} else {
|
||||
accounts.push(
|
||||
...(await User.manyFromSql(
|
||||
or(
|
||||
like(Users.displayName, `%${q}%`),
|
||||
like(Users.username, `%${q}%`),
|
||||
following && self
|
||||
? sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${self.id} AND "Relationships"."following" = true)`
|
||||
: undefined,
|
||||
self ? not(eq(Users.id, self.id)) : undefined,
|
||||
),
|
||||
undefined,
|
||||
limit,
|
||||
offset,
|
||||
)),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
accounts.push(
|
||||
...(await User.manyFromSql(
|
||||
or(
|
||||
like(Users.displayName, `%${q}%`),
|
||||
like(Users.username, `%${q}%`),
|
||||
following && self
|
||||
? sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${self.id} AND "Relationships"."following" = true)`
|
||||
: undefined,
|
||||
self ? not(eq(Users.id, self.id)) : undefined,
|
||||
),
|
||||
undefined,
|
||||
limit,
|
||||
offset,
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
// Sort accounts by closest match
|
||||
// Returns array of numbers (indexes of accounts array)
|
||||
const indexOfCorrectSort = stringComparison.jaccardIndex
|
||||
.sortMatch(
|
||||
q,
|
||||
accounts.map((acct) => acct.getAcct()),
|
||||
)
|
||||
.map((sort) => sort.index);
|
||||
const indexOfCorrectSort = stringComparison.jaccardIndex
|
||||
.sortMatch(
|
||||
q,
|
||||
accounts.map((acct) => acct.getAcct()),
|
||||
)
|
||||
.map((sort) => sort.index);
|
||||
|
||||
const result = indexOfCorrectSort.map((index) => accounts[index]);
|
||||
const result = indexOfCorrectSort.map((index) => accounts[index]);
|
||||
|
||||
return jsonResponse(result.map((acct) => acct.toAPI()));
|
||||
},
|
||||
);
|
||||
return jsonResponse(result.map((acct) => acct.toAPI()));
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { sanitizeHtml, sanitizedHtmlStrip } from "@sanitization";
|
||||
import { config } from "config-manager";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import ISO6391 from "iso-639-1";
|
||||
import { MediaBackendType } from "media-manager";
|
||||
import type { MediaBackend } from "media-manager";
|
||||
|
|
@ -28,274 +30,295 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
display_name: z
|
||||
.string()
|
||||
.min(3)
|
||||
.trim()
|
||||
.max(config.validation.max_displayname_size)
|
||||
.optional(),
|
||||
note: z
|
||||
.string()
|
||||
.min(0)
|
||||
.max(config.validation.max_bio_size)
|
||||
.trim()
|
||||
.optional(),
|
||||
avatar: z.instanceof(File).optional(),
|
||||
header: z.instanceof(File).optional(),
|
||||
locked: z.boolean().optional(),
|
||||
bot: z.boolean().optional(),
|
||||
discoverable: z.boolean().optional(),
|
||||
source: z
|
||||
.object({
|
||||
privacy: z
|
||||
.enum(["public", "unlisted", "private", "direct"])
|
||||
.optional(),
|
||||
sensitive: z.boolean().optional(),
|
||||
language: z
|
||||
.enum(ISO6391.getAllCodes() as [string, ...string[]])
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
fields_attributes: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
display_name: z
|
||||
.string()
|
||||
.min(3)
|
||||
.trim()
|
||||
.max(config.validation.max_displayname_size)
|
||||
.optional(),
|
||||
note: z
|
||||
.string()
|
||||
.min(0)
|
||||
.max(config.validation.max_bio_size)
|
||||
.trim()
|
||||
.optional(),
|
||||
avatar: z.instanceof(File).optional(),
|
||||
header: z.instanceof(File).optional(),
|
||||
locked: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
bot: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
discoverable: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
source: z
|
||||
.object({
|
||||
privacy: z
|
||||
.enum(["public", "unlisted", "private", "direct"])
|
||||
.optional(),
|
||||
sensitive: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(config.validation.max_field_name_size),
|
||||
value: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(config.validation.max_field_value_size),
|
||||
}),
|
||||
)
|
||||
.max(config.validation.max_field_count)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const config = await extraData.configManager.getConfig();
|
||||
const self = user.getUser();
|
||||
|
||||
const {
|
||||
display_name,
|
||||
note,
|
||||
avatar,
|
||||
header,
|
||||
locked,
|
||||
bot,
|
||||
discoverable,
|
||||
source,
|
||||
fields_attributes,
|
||||
} = extraData.parsedRequest;
|
||||
|
||||
const sanitizedNote = await sanitizeHtml(note ?? "");
|
||||
|
||||
const sanitizedDisplayName = await sanitizedHtmlStrip(
|
||||
display_name ?? "",
|
||||
);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
if (display_name) {
|
||||
// Check if display name doesnt match filters
|
||||
if (
|
||||
config.filters.displayname.some((filter) =>
|
||||
sanitizedDisplayName.match(filter),
|
||||
)
|
||||
) {
|
||||
return errorResponse(
|
||||
"Display name contains blocked words",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
self.displayName = sanitizedDisplayName;
|
||||
}
|
||||
|
||||
if (note && self.source) {
|
||||
// Check if bio doesnt match filters
|
||||
if (
|
||||
config.filters.bio.some((filter) => sanitizedNote.match(filter))
|
||||
) {
|
||||
return errorResponse("Bio contains blocked words", 422);
|
||||
}
|
||||
|
||||
self.source.note = sanitizedNote;
|
||||
self.note = await contentToHtml({
|
||||
"text/markdown": {
|
||||
content: sanitizedNote,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (source?.privacy) {
|
||||
self.source.privacy = source.privacy;
|
||||
}
|
||||
|
||||
if (source?.sensitive) {
|
||||
self.source.sensitive = source.sensitive;
|
||||
}
|
||||
|
||||
if (source?.language) {
|
||||
self.source.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,
|
||||
);
|
||||
}
|
||||
|
||||
const { path } = await mediaManager.addFile(avatar);
|
||||
|
||||
self.avatar = getUrl(path, 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,
|
||||
);
|
||||
}
|
||||
|
||||
const { path } = await mediaManager.addFile(header);
|
||||
|
||||
self.header = getUrl(path, config);
|
||||
}
|
||||
|
||||
if (locked) {
|
||||
self.isLocked = locked;
|
||||
}
|
||||
|
||||
if (bot) {
|
||||
self.isBot = bot;
|
||||
}
|
||||
|
||||
if (discoverable) {
|
||||
self.isDiscoverable = discoverable;
|
||||
}
|
||||
|
||||
const fieldEmojis: EmojiWithInstance[] = [];
|
||||
|
||||
if (fields_attributes) {
|
||||
self.fields = [];
|
||||
self.source.fields = [];
|
||||
for (const field of fields_attributes) {
|
||||
// Can be Markdown or plaintext, also has emojis
|
||||
const parsedName = await contentToHtml({
|
||||
"text/markdown": {
|
||||
content: field.name,
|
||||
},
|
||||
});
|
||||
|
||||
const parsedValue = await contentToHtml({
|
||||
"text/markdown": {
|
||||
content: field.value,
|
||||
},
|
||||
});
|
||||
|
||||
// Parse emojis
|
||||
const nameEmojis = await parseEmojis(parsedName);
|
||||
const valueEmojis = await parseEmojis(parsedValue);
|
||||
|
||||
fieldEmojis.push(...nameEmojis, ...valueEmojis);
|
||||
|
||||
// Replace fields
|
||||
self.fields.push({
|
||||
key: {
|
||||
"text/html": {
|
||||
content: parsedName,
|
||||
},
|
||||
},
|
||||
value: {
|
||||
"text/html": {
|
||||
content: parsedValue,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
self.source.fields.push({
|
||||
name: field.name,
|
||||
value: field.value,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Parse emojis
|
||||
const displaynameEmojis = await parseEmojis(sanitizedDisplayName);
|
||||
const noteEmojis = await parseEmojis(sanitizedNote);
|
||||
|
||||
self.emojis = [...displaynameEmojis, ...noteEmojis, ...fieldEmojis];
|
||||
|
||||
// Deduplicate emojis
|
||||
self.emojis = self.emojis.filter(
|
||||
(emoji, index, self) =>
|
||||
self.findIndex((e) => e.id === emoji.id) === index,
|
||||
);
|
||||
|
||||
await db
|
||||
.update(Users)
|
||||
.set({
|
||||
displayName: self.displayName,
|
||||
note: self.note,
|
||||
avatar: self.avatar,
|
||||
header: self.header,
|
||||
fields: self.fields,
|
||||
isLocked: self.isLocked,
|
||||
isBot: self.isBot,
|
||||
isDiscoverable: self.isDiscoverable,
|
||||
source: self.source || undefined,
|
||||
.transform((v) =>
|
||||
["true", "1", "on"].includes(v.toLowerCase()),
|
||||
)
|
||||
.optional(),
|
||||
language: z
|
||||
.enum(ISO6391.getAllCodes() as [string, ...string[]])
|
||||
.optional(),
|
||||
})
|
||||
.where(eq(Users.id, self.id));
|
||||
.optional(),
|
||||
fields_attributes: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(config.validation.max_field_name_size),
|
||||
value: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(config.validation.max_field_value_size),
|
||||
}),
|
||||
)
|
||||
.max(config.validation.max_field_count)
|
||||
.optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
// Connect emojis, if any
|
||||
for (const emoji of self.emojis) {
|
||||
await db
|
||||
.delete(EmojiToUser)
|
||||
.where(
|
||||
and(
|
||||
eq(EmojiToUser.emojiId, emoji.id),
|
||||
eq(EmojiToUser.userId, self.id),
|
||||
),
|
||||
)
|
||||
.execute();
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user } = context.req.valid("header");
|
||||
const {
|
||||
display_name,
|
||||
note,
|
||||
avatar,
|
||||
header,
|
||||
locked,
|
||||
bot,
|
||||
discoverable,
|
||||
source,
|
||||
fields_attributes,
|
||||
} = context.req.valid("form");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const self = user.getUser();
|
||||
|
||||
const sanitizedNote = await sanitizeHtml(note ?? "");
|
||||
|
||||
const sanitizedDisplayName = await sanitizedHtmlStrip(
|
||||
display_name ?? "",
|
||||
);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
if (display_name) {
|
||||
// Check if display name doesnt match filters
|
||||
if (
|
||||
config.filters.displayname.some((filter) =>
|
||||
sanitizedDisplayName.match(filter),
|
||||
)
|
||||
) {
|
||||
return errorResponse(
|
||||
"Display name contains blocked words",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
self.displayName = sanitizedDisplayName;
|
||||
}
|
||||
|
||||
if (note && self.source) {
|
||||
// Check if bio doesnt match filters
|
||||
if (
|
||||
config.filters.bio.some((filter) =>
|
||||
sanitizedNote.match(filter),
|
||||
)
|
||||
) {
|
||||
return errorResponse("Bio contains blocked words", 422);
|
||||
}
|
||||
|
||||
self.source.note = sanitizedNote;
|
||||
self.note = await contentToHtml({
|
||||
"text/markdown": {
|
||||
content: sanitizedNote,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (source?.privacy) {
|
||||
self.source.privacy = source.privacy;
|
||||
}
|
||||
|
||||
if (source?.sensitive) {
|
||||
self.source.sensitive = source.sensitive;
|
||||
}
|
||||
|
||||
if (source?.language) {
|
||||
self.source.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,
|
||||
);
|
||||
}
|
||||
|
||||
const { path } = await mediaManager.addFile(avatar);
|
||||
|
||||
self.avatar = getUrl(path, 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,
|
||||
);
|
||||
}
|
||||
|
||||
const { path } = await mediaManager.addFile(header);
|
||||
|
||||
self.header = getUrl(path, config);
|
||||
}
|
||||
|
||||
if (locked) {
|
||||
self.isLocked = locked;
|
||||
}
|
||||
|
||||
if (bot) {
|
||||
self.isBot = bot;
|
||||
}
|
||||
|
||||
if (discoverable) {
|
||||
self.isDiscoverable = discoverable;
|
||||
}
|
||||
|
||||
const fieldEmojis: EmojiWithInstance[] = [];
|
||||
|
||||
if (fields_attributes) {
|
||||
self.fields = [];
|
||||
self.source.fields = [];
|
||||
for (const field of fields_attributes) {
|
||||
// Can be Markdown or plaintext, also has emojis
|
||||
const parsedName = await contentToHtml({
|
||||
"text/markdown": {
|
||||
content: field.name,
|
||||
},
|
||||
});
|
||||
|
||||
const parsedValue = await contentToHtml({
|
||||
"text/markdown": {
|
||||
content: field.value,
|
||||
},
|
||||
});
|
||||
|
||||
// Parse emojis
|
||||
const nameEmojis = await parseEmojis(parsedName);
|
||||
const valueEmojis = await parseEmojis(parsedValue);
|
||||
|
||||
fieldEmojis.push(...nameEmojis, ...valueEmojis);
|
||||
|
||||
// Replace fields
|
||||
self.fields.push({
|
||||
key: {
|
||||
"text/html": {
|
||||
content: parsedName,
|
||||
},
|
||||
},
|
||||
value: {
|
||||
"text/html": {
|
||||
content: parsedValue,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
self.source.fields.push({
|
||||
name: field.name,
|
||||
value: field.value,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Parse emojis
|
||||
const displaynameEmojis = await parseEmojis(sanitizedDisplayName);
|
||||
const noteEmojis = await parseEmojis(sanitizedNote);
|
||||
|
||||
self.emojis = [...displaynameEmojis, ...noteEmojis, ...fieldEmojis];
|
||||
|
||||
// Deduplicate emojis
|
||||
self.emojis = self.emojis.filter(
|
||||
(emoji, index, self) =>
|
||||
self.findIndex((e) => e.id === emoji.id) === index,
|
||||
);
|
||||
|
||||
await db
|
||||
.insert(EmojiToUser)
|
||||
.values({
|
||||
emojiId: emoji.id,
|
||||
userId: self.id,
|
||||
.update(Users)
|
||||
.set({
|
||||
displayName: self.displayName,
|
||||
note: self.note,
|
||||
avatar: self.avatar,
|
||||
header: self.header,
|
||||
fields: self.fields,
|
||||
isLocked: self.isLocked,
|
||||
isBot: self.isBot,
|
||||
isDiscoverable: self.isDiscoverable,
|
||||
source: self.source || undefined,
|
||||
})
|
||||
.execute();
|
||||
}
|
||||
.where(eq(Users.id, self.id));
|
||||
|
||||
const output = await User.fromId(self.id);
|
||||
if (!output) return errorResponse("Couldn't edit user", 500);
|
||||
// Connect emojis, if any
|
||||
for (const emoji of self.emojis) {
|
||||
await db
|
||||
.delete(EmojiToUser)
|
||||
.where(
|
||||
and(
|
||||
eq(EmojiToUser.emojiId, emoji.id),
|
||||
eq(EmojiToUser.userId, self.id),
|
||||
),
|
||||
)
|
||||
.execute();
|
||||
|
||||
return jsonResponse(output.toAPI());
|
||||
},
|
||||
);
|
||||
await db
|
||||
.insert(EmojiToUser)
|
||||
.values({
|
||||
emojiId: emoji.id,
|
||||
userId: self.id,
|
||||
})
|
||||
.execute();
|
||||
}
|
||||
|
||||
const output = await User.fromId(self.id);
|
||||
if (!output) return errorResponse("Couldn't edit user", 500);
|
||||
|
||||
return jsonResponse(output.toAPI());
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
|
|
@ -14,12 +15,17 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute((req, matchedRoute, extraData) => {
|
||||
// TODO: Add checks for disabled or not email verified accounts
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
// TODO: Add checks for disabled/unverified accounts
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
const { user } = extraData.auth;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
return jsonResponse(user.toAPI(true));
|
||||
});
|
||||
return jsonResponse(user.toAPI(true));
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { randomBytes } from "node:crypto";
|
||||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Applications } from "~drizzle/schema";
|
||||
|
|
@ -17,43 +19,46 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
client_name: z.string().trim().min(1).max(100),
|
||||
redirect_uris: z.string().min(0).max(2000).url(),
|
||||
scopes: z.string().min(1).max(200),
|
||||
website: z.string().min(0).max(2000).url().optional(),
|
||||
});
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
client_name: z.string().trim().min(1).max(100),
|
||||
redirect_uris: z.string().min(0).max(2000).url(),
|
||||
scopes: z.string().min(1).max(200),
|
||||
website: z.string().min(0).max(2000).url().optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new application to obtain OAuth 2 credentials
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { client_name, redirect_uris, scopes, website } =
|
||||
extraData.parsedRequest;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
async (context) => {
|
||||
const { client_name, redirect_uris, scopes, website } =
|
||||
context.req.valid("form");
|
||||
|
||||
const app = (
|
||||
await db
|
||||
.insert(Applications)
|
||||
.values({
|
||||
name: client_name || "",
|
||||
redirectUri: decodeURIComponent(redirect_uris) || "",
|
||||
scopes: scopes || "read",
|
||||
website: website || null,
|
||||
clientId: randomBytes(32).toString("base64url"),
|
||||
secret: randomBytes(64).toString("base64url"),
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
const app = (
|
||||
await db
|
||||
.insert(Applications)
|
||||
.values({
|
||||
name: client_name || "",
|
||||
redirectUri: decodeURIComponent(redirect_uris) || "",
|
||||
scopes: scopes || "read",
|
||||
website: website || null,
|
||||
clientId: randomBytes(32).toString("base64url"),
|
||||
secret: randomBytes(64).toString("base64url"),
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
|
||||
return jsonResponse({
|
||||
id: app.id,
|
||||
name: app.name,
|
||||
website: app.website,
|
||||
client_id: app.clientId,
|
||||
client_secret: app.secret,
|
||||
redirect_uri: app.redirectUri,
|
||||
vapid_link: app.vapidKey,
|
||||
});
|
||||
},
|
||||
);
|
||||
return jsonResponse({
|
||||
id: app.id,
|
||||
name: app.name,
|
||||
website: app.website,
|
||||
client_id: app.clientId,
|
||||
client_secret: app.secret,
|
||||
redirect_uri: app.redirectUri,
|
||||
vapid_link: app.vapidKey,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { getFromToken } from "~database/entities/Application";
|
||||
|
||||
export const meta = applyConfig({
|
||||
|
|
@ -14,24 +15,27 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns OAuth2 credentials
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const { user, token } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user, token } = context.req.valid("header");
|
||||
|
||||
if (!token) return errorResponse("Unauthorized", 401);
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
if (!token) return errorResponse("Unauthorized", 401);
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const application = await getFromToken(token);
|
||||
const application = await getFromToken(token);
|
||||
|
||||
if (!application) return errorResponse("Unauthorized", 401);
|
||||
if (!application) return errorResponse("Unauthorized", 401);
|
||||
|
||||
return jsonResponse({
|
||||
name: application.name,
|
||||
website: application.website,
|
||||
vapid_key: application.vapidKey,
|
||||
redirect_uris: application.redirectUri,
|
||||
scopes: application.scopes,
|
||||
});
|
||||
});
|
||||
return jsonResponse({
|
||||
name: application.name,
|
||||
website: application.website,
|
||||
vapid_key: application.vapidKey,
|
||||
redirect_uris: application.redirectUri,
|
||||
scopes: application.scopes,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { apiRoute, applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
|
|
@ -18,38 +20,46 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { max_id, since_id, min_id, limit } =
|
||||
context.req.valid("query");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
const { max_id, since_id, min_id, limit } = extraData.parsedRequest;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { objects: blocks, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${user.id} AND "Relationships"."blocking" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
);
|
||||
const { objects: blocks, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${user.id} AND "Relationships"."blocking" = true)`,
|
||||
),
|
||||
limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
blocks.map((u) => u.toAPI()),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
return jsonResponse(
|
||||
blocks.map((u) => u.toAPI()),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig } from "@api";
|
||||
import { jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { emojiToAPI } from "~database/entities/Emoji";
|
||||
import { db } from "~drizzle/db";
|
||||
|
||||
|
|
@ -15,15 +16,16 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async () => {
|
||||
const emojis = await db.query.Emojis.findMany({
|
||||
where: (emoji, { isNull }) => isNull(emoji.instanceId),
|
||||
with: {
|
||||
instance: true,
|
||||
},
|
||||
});
|
||||
export default (app: Hono) =>
|
||||
app.on(meta.allowedMethods, meta.route, async () => {
|
||||
const emojis = await db.query.Emojis.findMany({
|
||||
where: (emoji, { isNull }) => isNull(emoji.instanceId),
|
||||
with: {
|
||||
instance: true,
|
||||
},
|
||||
});
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(emojis.map((emoji) => emojiToAPI(emoji))),
|
||||
);
|
||||
});
|
||||
return jsonResponse(
|
||||
await Promise.all(emojis.map((emoji) => emojiToAPI(emoji))),
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { apiRoute, applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Notes } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
|
|
@ -17,38 +19,49 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { max_id, since_id, min_id, limit } =
|
||||
context.req.valid("query");
|
||||
|
||||
const { limit, max_id, min_id, since_id } = extraData.parsedRequest;
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { objects, link } = await Timeline.getNoteTimeline(
|
||||
and(
|
||||
max_id ? lt(Notes.id, max_id) : undefined,
|
||||
since_id ? gte(Notes.id, since_id) : undefined,
|
||||
min_id ? gt(Notes.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Likes" WHERE "Likes"."likedId" = ${Notes.id} AND "Likes"."likerId" = ${user.id})`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
);
|
||||
const { objects: favourites, link } =
|
||||
await Timeline.getNoteTimeline(
|
||||
and(
|
||||
max_id ? lt(Notes.id, max_id) : undefined,
|
||||
since_id ? gte(Notes.id, since_id) : undefined,
|
||||
min_id ? gt(Notes.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Likes" WHERE "Likes"."likedId" = ${Notes.id} AND "Likes"."likerId" = ${user.id})`,
|
||||
),
|
||||
limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map(async (note) => note.toAPI(user))),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
return jsonResponse(
|
||||
await Promise.all(
|
||||
favourites.map(async (note) => note.toAPI(user)),
|
||||
),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
100
server/api/api/v1/follow_requests/:account_id/authorize.ts
Normal file
100
server/api/api/v1/follow_requests/:account_id/authorize.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
checkForBidirectionalRelationships,
|
||||
relationshipToAPI,
|
||||
} from "~database/entities/Relationship";
|
||||
import {
|
||||
getRelationshipToOtherUser,
|
||||
sendFollowAccept,
|
||||
} from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
route: "/api/v1/follow_requests/:account_id/authorize",
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
auth: {
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
account_id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { account_id } = context.req.valid("param");
|
||||
|
||||
const account = await User.fromId(account_id);
|
||||
|
||||
if (!account) return errorResponse("Account not found", 404);
|
||||
|
||||
// Check if there is a relationship on both sides
|
||||
await checkForBidirectionalRelationships(user, account);
|
||||
|
||||
// Authorize follow request
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
requested: false,
|
||||
following: true,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, user.id),
|
||||
eq(Relationships.ownerId, account.id),
|
||||
),
|
||||
);
|
||||
|
||||
// Update followedBy for other user
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
followedBy: true,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, account.id),
|
||||
eq(Relationships.ownerId, user.id),
|
||||
),
|
||||
);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
account,
|
||||
);
|
||||
|
||||
if (!foundRelationship)
|
||||
return errorResponse("Relationship not found", 404);
|
||||
|
||||
// Check if accepting remote follow
|
||||
if (account.isRemote()) {
|
||||
// Federate follow accept
|
||||
await sendFollowAccept(account, user);
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
100
server/api/api/v1/follow_requests/:account_id/reject.ts
Normal file
100
server/api/api/v1/follow_requests/:account_id/reject.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
checkForBidirectionalRelationships,
|
||||
relationshipToAPI,
|
||||
} from "~database/entities/Relationship";
|
||||
import {
|
||||
getRelationshipToOtherUser,
|
||||
sendFollowReject,
|
||||
} from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
route: "/api/v1/follow_requests/:account_id/reject",
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
auth: {
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
account_id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { account_id } = context.req.valid("param");
|
||||
|
||||
const account = await User.fromId(account_id);
|
||||
|
||||
if (!account) return errorResponse("Account not found", 404);
|
||||
|
||||
// Check if there is a relationship on both sides
|
||||
await checkForBidirectionalRelationships(user, account);
|
||||
|
||||
// Reject follow request
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
requested: false,
|
||||
following: false,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, user.id),
|
||||
eq(Relationships.ownerId, account.id),
|
||||
),
|
||||
);
|
||||
|
||||
// Update followedBy for other user
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
followedBy: false,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, account.id),
|
||||
eq(Relationships.ownerId, user.id),
|
||||
),
|
||||
);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(
|
||||
user,
|
||||
account,
|
||||
);
|
||||
|
||||
if (!foundRelationship)
|
||||
return errorResponse("Relationship not found", 404);
|
||||
|
||||
// Check if rejecting remote follow
|
||||
if (account.isRemote()) {
|
||||
// Federate follow reject
|
||||
await sendFollowReject(account, user);
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
},
|
||||
);
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import {
|
||||
checkForBidirectionalRelationships,
|
||||
relationshipToAPI,
|
||||
} from "~database/entities/Relationship";
|
||||
import {
|
||||
getRelationshipToOtherUser,
|
||||
sendFollowAccept,
|
||||
} from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
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;
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { account_id } = matchedRoute.params;
|
||||
|
||||
const account = await User.fromId(account_id);
|
||||
|
||||
if (!account) return errorResponse("Account not found", 404);
|
||||
|
||||
// Check if there is a relationship on both sides
|
||||
await checkForBidirectionalRelationships(user, account);
|
||||
|
||||
// Authorize follow request
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
requested: false,
|
||||
following: true,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, user.id),
|
||||
eq(Relationships.ownerId, account.id),
|
||||
),
|
||||
);
|
||||
|
||||
// Update followedBy for other user
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
followedBy: true,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, account.id),
|
||||
eq(Relationships.ownerId, user.id),
|
||||
),
|
||||
);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(user, account);
|
||||
|
||||
if (!foundRelationship) return errorResponse("Relationship not found", 404);
|
||||
|
||||
// Check if accepting remote follow
|
||||
if (account.isRemote()) {
|
||||
// Federate follow accept
|
||||
await sendFollowAccept(account, user);
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import {
|
||||
checkForBidirectionalRelationships,
|
||||
relationshipToAPI,
|
||||
} from "~database/entities/Relationship";
|
||||
import {
|
||||
getRelationshipToOtherUser,
|
||||
sendFollowReject,
|
||||
} from "~database/entities/User";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Relationships } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
||||
export const meta = applyConfig({
|
||||
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;
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { account_id } = matchedRoute.params;
|
||||
|
||||
const account = await User.fromId(account_id);
|
||||
|
||||
if (!account) return errorResponse("Account not found", 404);
|
||||
|
||||
// Check if there is a relationship on both sides
|
||||
await checkForBidirectionalRelationships(user, account);
|
||||
|
||||
// Reject follow request
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
requested: false,
|
||||
following: false,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, user.id),
|
||||
eq(Relationships.ownerId, account.id),
|
||||
),
|
||||
);
|
||||
|
||||
// Update followedBy for other user
|
||||
await db
|
||||
.update(Relationships)
|
||||
.set({
|
||||
followedBy: false,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(Relationships.subjectId, account.id),
|
||||
eq(Relationships.ownerId, user.id),
|
||||
),
|
||||
);
|
||||
|
||||
const foundRelationship = await getRelationshipToOtherUser(user, account);
|
||||
|
||||
if (!foundRelationship) return errorResponse("Relationship not found", 404);
|
||||
|
||||
// Check if rejecting remote follow
|
||||
if (account.isRemote()) {
|
||||
// Federate follow reject
|
||||
await sendFollowReject(account, user);
|
||||
}
|
||||
|
||||
return jsonResponse(relationshipToAPI(foundRelationship));
|
||||
});
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { apiRoute, applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
|
|
@ -17,38 +19,47 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(20),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { max_id, since_id, min_id, limit } =
|
||||
context.req.valid("query");
|
||||
|
||||
const { limit, max_id, min_id, since_id } = extraData.parsedRequest;
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { objects, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${user.id} AND "Relationships"."ownerId" = ${Users.id} AND "Relationships"."requested" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
);
|
||||
const { objects: followRequests, link } =
|
||||
await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${user.id} AND "Relationships"."ownerId" = ${Users.id} AND "Relationships"."requested" = true)`,
|
||||
),
|
||||
limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
objects.map((user) => user.toAPI()),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
return jsonResponse(
|
||||
followRequests.map((u) => u.toAPI()),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { dualLogger } from "@loggers";
|
||||
import { jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { getMarkdownRenderer } from "~database/entities/Status";
|
||||
import { config } from "~packages/config-manager";
|
||||
import { LogLevel } from "~packages/log-manager";
|
||||
|
||||
export const meta = applyConfig({
|
||||
|
|
@ -16,32 +18,31 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const config = await extraData.configManager.getConfig();
|
||||
export default (app: Hono) =>
|
||||
app.on(meta.allowedMethods, meta.route, auth(meta.auth), async () => {
|
||||
let extended_description = (await getMarkdownRenderer()).render(
|
||||
"This is a [Lysand](https://lysand.org) server with the default extended description.",
|
||||
);
|
||||
let lastModified = new Date(2024, 0, 0);
|
||||
|
||||
let extended_description = (await getMarkdownRenderer()).render(
|
||||
"This is a [Lysand](https://lysand.org) server with the default extended description.",
|
||||
);
|
||||
let lastModified = new Date(2024, 0, 0);
|
||||
const extended_description_file = Bun.file(
|
||||
config.instance.extended_description_path,
|
||||
);
|
||||
|
||||
const extended_description_file = Bun.file(
|
||||
config.instance.extended_description_path,
|
||||
);
|
||||
if (await extended_description_file.exists()) {
|
||||
extended_description =
|
||||
(await getMarkdownRenderer()).render(
|
||||
(await extended_description_file.text().catch(async (e) => {
|
||||
await dualLogger.logError(LogLevel.ERROR, "Routes", e);
|
||||
return "";
|
||||
})) ||
|
||||
"This is a [Lysand](https://lysand.org) server with the default extended description.",
|
||||
) || "";
|
||||
lastModified = new Date(extended_description_file.lastModified);
|
||||
}
|
||||
|
||||
if (await extended_description_file.exists()) {
|
||||
extended_description =
|
||||
(await getMarkdownRenderer()).render(
|
||||
(await extended_description_file.text().catch(async (e) => {
|
||||
await dualLogger.logError(LogLevel.ERROR, "Routes", e);
|
||||
return "";
|
||||
})) ||
|
||||
"This is a [Lysand](https://lysand.org) server with the default extended description.",
|
||||
) || "";
|
||||
lastModified = new Date(extended_description_file.lastModified);
|
||||
}
|
||||
|
||||
return jsonResponse({
|
||||
updated_at: lastModified.toISOString(),
|
||||
content: extended_description,
|
||||
return jsonResponse({
|
||||
updated_at: lastModified.toISOString(),
|
||||
content: extended_description,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { jsonResponse, proxyUrl } from "@response";
|
||||
import { and, count, countDistinct, eq, gte, isNull, sql } from "drizzle-orm";
|
||||
import { and, count, eq, isNull } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Instances, Notes, Users } from "~drizzle/schema";
|
||||
import { Instances, Users } from "~drizzle/schema";
|
||||
import manifest from "~package.json";
|
||||
import { config } from "~packages/config-manager";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
import type { Instance as APIInstance } from "~types/mastodon/instance";
|
||||
|
||||
|
|
@ -19,177 +22,145 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const config = await extraData.configManager.getConfig();
|
||||
export default (app: Hono) =>
|
||||
app.on(meta.allowedMethods, meta.route, auth(meta.auth), async () => {
|
||||
// Get software version from package.json
|
||||
const version = manifest.version;
|
||||
|
||||
// Get software version from package.json
|
||||
const version = manifest.version;
|
||||
const statusCount = await Note.getCount();
|
||||
|
||||
const statusCount = (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Notes)
|
||||
.where(
|
||||
sql`EXISTS (SELECT 1 FROM "Users" WHERE "Users"."id" = ${Notes.authorId} AND "Users"."instanceId" IS NULL)`,
|
||||
)
|
||||
)[0].count;
|
||||
const userCount = await User.getCount();
|
||||
|
||||
const userCount = (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Users)
|
||||
.where(isNull(Users.instanceId))
|
||||
)[0].count;
|
||||
const contactAccount = await User.fromSql(
|
||||
and(isNull(Users.instanceId), eq(Users.isAdmin, true)),
|
||||
);
|
||||
|
||||
const contactAccount = await User.fromSql(
|
||||
and(isNull(Users.instanceId), eq(Users.isAdmin, true)),
|
||||
);
|
||||
const monthlyActiveUsers = await User.getActiveInPeriod(
|
||||
30 * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
|
||||
const monthlyActiveUsers = (
|
||||
await db
|
||||
.select({
|
||||
count: countDistinct(Users),
|
||||
})
|
||||
.from(Users)
|
||||
.leftJoin(Notes, eq(Users.id, Notes.authorId))
|
||||
.where(
|
||||
and(
|
||||
isNull(Users.instanceId),
|
||||
gte(
|
||||
Notes.createdAt,
|
||||
new Date(
|
||||
Date.now() - 30 * 24 * 60 * 60 * 1000,
|
||||
).toISOString(),
|
||||
),
|
||||
),
|
||||
)
|
||||
)[0].count;
|
||||
const knownDomainsCount = (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Instances)
|
||||
)[0].count;
|
||||
|
||||
const knownDomainsCount = (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Instances)
|
||||
)[0].count;
|
||||
|
||||
// TODO: fill in more values
|
||||
return jsonResponse({
|
||||
approval_required: false,
|
||||
configuration: {
|
||||
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,
|
||||
},
|
||||
},
|
||||
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: proxyUrl(config.instance.logo),
|
||||
banner: proxyUrl(config.instance.banner) ?? "",
|
||||
title: config.instance.name,
|
||||
uri: config.http.base_url,
|
||||
urls: {
|
||||
streaming_api: "",
|
||||
},
|
||||
version: "4.3.0-alpha.3+glitch",
|
||||
lysand_version: version,
|
||||
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",
|
||||
],
|
||||
federation: {
|
||||
enabled: true,
|
||||
exclusions: false,
|
||||
mrf_policies: [],
|
||||
mrf_simple: {
|
||||
accept: [],
|
||||
avatar_removal: [],
|
||||
background_removal: [],
|
||||
banner_removal: [],
|
||||
federated_timeline_removal: [],
|
||||
followers_only: [],
|
||||
media_nsfw: [],
|
||||
media_removal: [],
|
||||
reject: [],
|
||||
reject_deletes: [],
|
||||
report_removal: [],
|
||||
},
|
||||
mrf_simple_info: {
|
||||
media_nsfw: {},
|
||||
reject: {},
|
||||
},
|
||||
quarantined_instances: [],
|
||||
quarantined_instances_info: {
|
||||
quarantined_instances: {},
|
||||
},
|
||||
// TODO: fill in more values
|
||||
return jsonResponse({
|
||||
approval_required: false,
|
||||
configuration: {
|
||||
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: config.validation.min_poll_duration,
|
||||
},
|
||||
fields_limits: {
|
||||
max_fields: config.validation.max_field_count,
|
||||
max_remote_fields: 9999,
|
||||
name_length: config.validation.max_field_name_size,
|
||||
value_length: config.validation.max_field_value_size,
|
||||
statuses: {
|
||||
characters_reserved_per_url: 0,
|
||||
max_characters: config.validation.max_note_size,
|
||||
max_media_attachments:
|
||||
config.validation.max_media_attachments,
|
||||
},
|
||||
post_formats: [
|
||||
"text/plain",
|
||||
"text/html",
|
||||
"text/markdown",
|
||||
"text/x.misskeymarkdown",
|
||||
],
|
||||
privileged_staff: false,
|
||||
},
|
||||
description: config.instance.description,
|
||||
email: "",
|
||||
invites_enabled: false,
|
||||
registrations: config.signups.registration,
|
||||
languages: ["en"],
|
||||
rules: config.signups.rules.map((r, index) => ({
|
||||
id: String(index),
|
||||
text: r,
|
||||
})),
|
||||
stats: {
|
||||
mau: monthlyActiveUsers,
|
||||
domain_count: knownDomainsCount,
|
||||
status_count: statusCount,
|
||||
user_count: userCount,
|
||||
},
|
||||
vapid_public_key: "",
|
||||
},
|
||||
contact_account: contactAccount?.toAPI() || undefined,
|
||||
} satisfies APIInstance & {
|
||||
banner: string;
|
||||
lysand_version: string;
|
||||
pleroma: object;
|
||||
thumbnail: proxyUrl(config.instance.logo),
|
||||
banner: proxyUrl(config.instance.banner) ?? "",
|
||||
title: config.instance.name,
|
||||
uri: config.http.base_url,
|
||||
urls: {
|
||||
streaming_api: "",
|
||||
},
|
||||
version: "4.3.0-alpha.3+glitch",
|
||||
lysand_version: version,
|
||||
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",
|
||||
],
|
||||
federation: {
|
||||
enabled: true,
|
||||
exclusions: false,
|
||||
mrf_policies: [],
|
||||
mrf_simple: {
|
||||
accept: [],
|
||||
avatar_removal: [],
|
||||
background_removal: [],
|
||||
banner_removal: [],
|
||||
federated_timeline_removal: [],
|
||||
followers_only: [],
|
||||
media_nsfw: [],
|
||||
media_removal: [],
|
||||
reject: [],
|
||||
reject_deletes: [],
|
||||
report_removal: [],
|
||||
},
|
||||
mrf_simple_info: {
|
||||
media_nsfw: {},
|
||||
reject: {},
|
||||
},
|
||||
quarantined_instances: [],
|
||||
quarantined_instances_info: {
|
||||
quarantined_instances: {},
|
||||
},
|
||||
},
|
||||
fields_limits: {
|
||||
max_fields: config.validation.max_field_count,
|
||||
max_remote_fields: 9999,
|
||||
name_length: config.validation.max_field_name_size,
|
||||
value_length: config.validation.max_field_value_size,
|
||||
},
|
||||
post_formats: [
|
||||
"text/plain",
|
||||
"text/html",
|
||||
"text/markdown",
|
||||
"text/x.misskeymarkdown",
|
||||
],
|
||||
privileged_staff: false,
|
||||
},
|
||||
stats: {
|
||||
mau: monthlyActiveUsers,
|
||||
},
|
||||
vapid_public_key: "",
|
||||
},
|
||||
contact_account: contactAccount?.toAPI() || undefined,
|
||||
} satisfies APIInstance & {
|
||||
banner: string;
|
||||
lysand_version: string;
|
||||
pleroma: object;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { config } from "~packages/config-manager";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
|
|
@ -13,14 +15,18 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const config = await extraData.configManager.getConfig();
|
||||
|
||||
return jsonResponse(
|
||||
config.signups.rules.map((rule, index) => ({
|
||||
id: String(index),
|
||||
text: rule,
|
||||
hint: "",
|
||||
})),
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
return jsonResponse(
|
||||
config.signups.rules.map((rule, index) => ({
|
||||
id: String(index),
|
||||
text: rule,
|
||||
hint: "",
|
||||
})),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -53,16 +53,20 @@ describe(meta.route, () => {
|
|||
|
||||
test("should create markers", async () => {
|
||||
const response = await sendTestRequest(
|
||||
new Request(new URL(meta.route, config.http.base_url), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
new Request(
|
||||
new URL(
|
||||
`${meta.route}?${new URLSearchParams({
|
||||
"home[last_read_id]": timeline[0].id,
|
||||
})}`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
},
|
||||
},
|
||||
body: JSON.stringify({
|
||||
"home[last_read_id]": timeline[0].id,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,16 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import {
|
||||
applyConfig,
|
||||
auth,
|
||||
handleZodError,
|
||||
idValidator,
|
||||
qs,
|
||||
qsQuery,
|
||||
} from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, count, eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { validator } from "hono/validator";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Markers } from "~drizzle/schema";
|
||||
|
|
@ -19,175 +29,188 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
timeline: z
|
||||
.array(z.enum(["home", "notifications"]))
|
||||
.max(2)
|
||||
.optional(),
|
||||
"home[last_read_id]": z.string().regex(idValidator).optional(),
|
||||
"notifications[last_read_id]": z.string().regex(idValidator).optional(),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
"timeline[]": z
|
||||
.array(z.enum(["home", "notifications"]))
|
||||
.max(2)
|
||||
.optional(),
|
||||
"home[last_read_id]": z.string().regex(idValidator).optional(),
|
||||
"notifications[last_read_id]": z.string().regex(idValidator).optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { "timeline[]": timeline } = context.req.valid("query");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
if (!user) {
|
||||
return errorResponse("Unauthorized", 401);
|
||||
}
|
||||
|
||||
switch (req.method) {
|
||||
case "GET": {
|
||||
const { timeline } = extraData.parsedRequest;
|
||||
switch (context.req.method) {
|
||||
case "GET": {
|
||||
if (!timeline) {
|
||||
return jsonResponse({});
|
||||
}
|
||||
|
||||
if (!timeline) {
|
||||
return jsonResponse({});
|
||||
const markers: APIMarker = {
|
||||
home: undefined,
|
||||
notifications: undefined,
|
||||
};
|
||||
|
||||
if (timeline.includes("home")) {
|
||||
const found = await db.query.Markers.findFirst({
|
||||
where: (marker, { and, eq }) =>
|
||||
and(
|
||||
eq(marker.userId, user.id),
|
||||
eq(marker.timeline, "home"),
|
||||
),
|
||||
});
|
||||
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "home"),
|
||||
),
|
||||
);
|
||||
|
||||
if (found?.noteId) {
|
||||
markers.home = {
|
||||
last_read_id: found.noteId,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(
|
||||
found.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (timeline.includes("notifications")) {
|
||||
const found = await db.query.Markers.findFirst({
|
||||
where: (marker, { and, eq }) =>
|
||||
and(
|
||||
eq(marker.userId, user.id),
|
||||
eq(marker.timeline, "notifications"),
|
||||
),
|
||||
});
|
||||
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "notifications"),
|
||||
),
|
||||
);
|
||||
|
||||
if (found?.notificationId) {
|
||||
markers.notifications = {
|
||||
last_read_id: found.notificationId,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(
|
||||
found.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return jsonResponse(markers);
|
||||
}
|
||||
|
||||
const markers: APIMarker = {
|
||||
home: undefined,
|
||||
notifications: undefined,
|
||||
};
|
||||
case "POST": {
|
||||
const {
|
||||
"home[last_read_id]": home_id,
|
||||
"notifications[last_read_id]": notifications_id,
|
||||
} = context.req.valid("query");
|
||||
|
||||
if (timeline.includes("home")) {
|
||||
const found = await db.query.Markers.findFirst({
|
||||
where: (marker, { and, eq }) =>
|
||||
and(
|
||||
eq(marker.userId, user.id),
|
||||
eq(marker.timeline, "home"),
|
||||
),
|
||||
});
|
||||
const markers: APIMarker = {
|
||||
home: undefined,
|
||||
notifications: undefined,
|
||||
};
|
||||
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "home"),
|
||||
),
|
||||
);
|
||||
if (home_id) {
|
||||
const insertedMarker = (
|
||||
await db
|
||||
.insert(Markers)
|
||||
.values({
|
||||
userId: user.id,
|
||||
timeline: "home",
|
||||
noteId: home_id,
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "home"),
|
||||
),
|
||||
);
|
||||
|
||||
if (found?.noteId) {
|
||||
markers.home = {
|
||||
last_read_id: found.noteId,
|
||||
last_read_id: home_id,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(found.createdAt).toISOString(),
|
||||
updated_at: new Date(
|
||||
insertedMarker.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (timeline.includes("notifications")) {
|
||||
const found = await db.query.Markers.findFirst({
|
||||
where: (marker, { and, eq }) =>
|
||||
and(
|
||||
eq(marker.userId, user.id),
|
||||
eq(marker.timeline, "notifications"),
|
||||
),
|
||||
});
|
||||
if (notifications_id) {
|
||||
const insertedMarker = (
|
||||
await db
|
||||
.insert(Markers)
|
||||
.values({
|
||||
userId: user.id,
|
||||
timeline: "notifications",
|
||||
notificationId: notifications_id,
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "notifications"),
|
||||
),
|
||||
);
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "notifications"),
|
||||
),
|
||||
);
|
||||
|
||||
if (found?.notificationId) {
|
||||
markers.notifications = {
|
||||
last_read_id: found.notificationId,
|
||||
last_read_id: notifications_id,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(found.createdAt).toISOString(),
|
||||
updated_at: new Date(
|
||||
insertedMarker.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return jsonResponse(markers);
|
||||
return jsonResponse(markers);
|
||||
}
|
||||
}
|
||||
case "POST": {
|
||||
const {
|
||||
"home[last_read_id]": home_id,
|
||||
"notifications[last_read_id]": notifications_id,
|
||||
} = extraData.parsedRequest;
|
||||
|
||||
const markers: APIMarker = {
|
||||
home: undefined,
|
||||
notifications: undefined,
|
||||
};
|
||||
|
||||
if (home_id) {
|
||||
const insertedMarker = (
|
||||
await db
|
||||
.insert(Markers)
|
||||
.values({
|
||||
userId: user.id,
|
||||
timeline: "home",
|
||||
noteId: home_id,
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "home"),
|
||||
),
|
||||
);
|
||||
|
||||
markers.home = {
|
||||
last_read_id: home_id,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(
|
||||
insertedMarker.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
if (notifications_id) {
|
||||
const insertedMarker = (
|
||||
await db
|
||||
.insert(Markers)
|
||||
.values({
|
||||
userId: user.id,
|
||||
timeline: "notifications",
|
||||
notificationId: notifications_id,
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
|
||||
const totalCount = await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Markers)
|
||||
.where(
|
||||
and(
|
||||
eq(Markers.userId, user.id),
|
||||
eq(Markers.timeline, "notifications"),
|
||||
),
|
||||
);
|
||||
|
||||
markers.notifications = {
|
||||
last_read_id: notifications_id,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(
|
||||
insertedMarker.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
return jsonResponse(markers);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
123
server/api/api/v1/media/:id/index.ts
Normal file
123
server/api/api/v1/media/:id/index.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse, response } from "@response";
|
||||
import { config } from "config-manager";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import type { MediaBackend } from "media-manager";
|
||||
import { MediaBackendType } from "media-manager";
|
||||
import { LocalMediaBackend, S3MediaBackend } from "media-manager";
|
||||
import { z } from "zod";
|
||||
import { attachmentToAPI, getUrl } from "~database/entities/Attachment";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Attachments } from "~drizzle/schema";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET", "PUT"],
|
||||
ratelimits: {
|
||||
max: 10,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/media/:id",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:media"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
form: z.object({
|
||||
thumbnail: z.instanceof(File).optional(),
|
||||
description: z
|
||||
.string()
|
||||
.max(config.validation.max_media_description_size)
|
||||
.optional(),
|
||||
focus: z.string().optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const foundAttachment = await db.query.Attachments.findFirst({
|
||||
where: (attachment, { eq }) => eq(attachment.id, id),
|
||||
});
|
||||
|
||||
if (!foundAttachment) {
|
||||
return errorResponse("Media not found", 404);
|
||||
}
|
||||
|
||||
switch (context.req.method) {
|
||||
case "GET": {
|
||||
if (foundAttachment.url) {
|
||||
return jsonResponse(attachmentToAPI(foundAttachment));
|
||||
}
|
||||
return response(null, 206);
|
||||
}
|
||||
case "PUT": {
|
||||
const { description, thumbnail } =
|
||||
context.req.valid("form");
|
||||
|
||||
let thumbnailUrl = foundAttachment.thumbnailUrl;
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
if (thumbnail) {
|
||||
const { path } = await mediaManager.addFile(thumbnail);
|
||||
thumbnailUrl = getUrl(path, config);
|
||||
}
|
||||
|
||||
const descriptionText =
|
||||
description || foundAttachment.description;
|
||||
|
||||
if (
|
||||
descriptionText !== foundAttachment.description ||
|
||||
thumbnailUrl !== foundAttachment.thumbnailUrl
|
||||
) {
|
||||
const newAttachment = (
|
||||
await db
|
||||
.update(Attachments)
|
||||
.set({
|
||||
description: descriptionText,
|
||||
thumbnailUrl,
|
||||
})
|
||||
.where(eq(Attachments.id, id))
|
||||
.returning()
|
||||
)[0];
|
||||
|
||||
return jsonResponse(attachmentToAPI(newAttachment));
|
||||
}
|
||||
|
||||
return jsonResponse(attachmentToAPI(foundAttachment));
|
||||
}
|
||||
}
|
||||
|
||||
return errorResponse("Method not allowed", 405);
|
||||
},
|
||||
);
|
||||
|
|
@ -1,119 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse, response } from "@response";
|
||||
import { config } from "config-manager";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { MediaBackend } from "media-manager";
|
||||
import { MediaBackendType } from "media-manager";
|
||||
import { LocalMediaBackend, S3MediaBackend } from "media-manager";
|
||||
import { z } from "zod";
|
||||
import { attachmentToAPI, getUrl } from "~database/entities/Attachment";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Attachments } from "~drizzle/schema";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET", "PUT"],
|
||||
ratelimits: {
|
||||
max: 10,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/media/:id",
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:media"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
thumbnail: z.instanceof(File).optional(),
|
||||
description: z
|
||||
.string()
|
||||
.max(config.validation.max_media_description_size)
|
||||
.optional(),
|
||||
focus: z.string().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Get media information
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
|
||||
if (!user) {
|
||||
return errorResponse("Unauthorized", 401);
|
||||
}
|
||||
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const foundAttachment = await db.query.Attachments.findFirst({
|
||||
where: (attachment, { eq }) => eq(attachment.id, id),
|
||||
});
|
||||
|
||||
if (!foundAttachment) {
|
||||
return errorResponse("Media not found", 404);
|
||||
}
|
||||
|
||||
const config = await extraData.configManager.getConfig();
|
||||
|
||||
switch (req.method) {
|
||||
case "GET": {
|
||||
if (foundAttachment.url) {
|
||||
return jsonResponse(attachmentToAPI(foundAttachment));
|
||||
}
|
||||
return response(null, 206);
|
||||
}
|
||||
case "PUT": {
|
||||
const { description, thumbnail } = extraData.parsedRequest;
|
||||
|
||||
let thumbnailUrl = foundAttachment.thumbnailUrl;
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
if (thumbnail) {
|
||||
const { path } = await mediaManager.addFile(thumbnail);
|
||||
thumbnailUrl = getUrl(path, config);
|
||||
}
|
||||
|
||||
const descriptionText =
|
||||
description || foundAttachment.description;
|
||||
|
||||
if (
|
||||
descriptionText !== foundAttachment.description ||
|
||||
thumbnailUrl !== foundAttachment.thumbnailUrl
|
||||
) {
|
||||
const newAttachment = (
|
||||
await db
|
||||
.update(Attachments)
|
||||
.set({
|
||||
description: descriptionText,
|
||||
thumbnailUrl,
|
||||
})
|
||||
.where(eq(Attachments.id, id))
|
||||
.returning()
|
||||
)[0];
|
||||
|
||||
return jsonResponse(attachmentToAPI(newAttachment));
|
||||
}
|
||||
|
||||
return jsonResponse(attachmentToAPI(foundAttachment));
|
||||
}
|
||||
}
|
||||
|
||||
return errorResponse("Method not allowed", 405);
|
||||
},
|
||||
);
|
||||
|
|
@ -1,7 +1,9 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { encode } from "blurhash";
|
||||
import { config } from "config-manager";
|
||||
import type { Hono } from "hono";
|
||||
import { MediaBackendType } from "media-manager";
|
||||
import type { MediaBackend } from "media-manager";
|
||||
import { LocalMediaBackend, S3MediaBackend } from "media-manager";
|
||||
|
|
@ -24,128 +26,125 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
file: z.instanceof(File),
|
||||
thumbnail: z.instanceof(File).optional(),
|
||||
description: z
|
||||
.string()
|
||||
.max(config.validation.max_media_description_size)
|
||||
.optional(),
|
||||
focus: z.string().optional(),
|
||||
});
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
file: z.instanceof(File),
|
||||
thumbnail: z.instanceof(File).optional(),
|
||||
description: z
|
||||
.string()
|
||||
.max(config.validation.max_media_description_size)
|
||||
.optional(),
|
||||
focus: z.string().optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Upload new media
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { file, thumbnail, description, focus } =
|
||||
context.req.valid("form");
|
||||
|
||||
if (!user) {
|
||||
return errorResponse("Unauthorized", 401);
|
||||
}
|
||||
if (file.size > config.validation.max_media_size) {
|
||||
return errorResponse(
|
||||
`File too large, max size is ${config.validation.max_media_size} bytes`,
|
||||
413,
|
||||
);
|
||||
}
|
||||
|
||||
const { file, thumbnail, description } = extraData.parsedRequest;
|
||||
if (
|
||||
config.validation.enforce_mime_types &&
|
||||
!config.validation.allowed_mime_types.includes(file.type)
|
||||
) {
|
||||
return errorResponse("Invalid file type", 415);
|
||||
}
|
||||
|
||||
const config = await extraData.configManager.getConfig();
|
||||
const sha256 = new Bun.SHA256();
|
||||
|
||||
if (file.size > config.validation.max_media_size) {
|
||||
return errorResponse(
|
||||
`File too large, max size is ${config.validation.max_media_size} bytes`,
|
||||
413,
|
||||
);
|
||||
}
|
||||
const isImage = file.type.startsWith("image/");
|
||||
|
||||
if (
|
||||
config.validation.enforce_mime_types &&
|
||||
!config.validation.allowed_mime_types.includes(file.type)
|
||||
) {
|
||||
return errorResponse("Invalid file type", 415);
|
||||
}
|
||||
const metadata = isImage
|
||||
? await sharp(await file.arrayBuffer()).metadata()
|
||||
: null;
|
||||
|
||||
const sha256 = new Bun.SHA256();
|
||||
const blurhash = await new Promise<string | null>((resolve) => {
|
||||
(async () =>
|
||||
sharp(await file.arrayBuffer())
|
||||
.raw()
|
||||
.ensureAlpha()
|
||||
.toBuffer((err, buffer) => {
|
||||
if (err) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const isImage = file.type.startsWith("image/");
|
||||
try {
|
||||
resolve(
|
||||
encode(
|
||||
new Uint8ClampedArray(buffer),
|
||||
metadata?.width ?? 0,
|
||||
metadata?.height ?? 0,
|
||||
4,
|
||||
4,
|
||||
) as string,
|
||||
);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
}))();
|
||||
});
|
||||
|
||||
const metadata = isImage
|
||||
? await sharp(await file.arrayBuffer()).metadata()
|
||||
: null;
|
||||
let url = "";
|
||||
|
||||
const blurhash = await new Promise<string | null>((resolve) => {
|
||||
(async () =>
|
||||
sharp(await file.arrayBuffer())
|
||||
.raw()
|
||||
.ensureAlpha()
|
||||
.toBuffer((err, buffer) => {
|
||||
if (err) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
let mediaManager: MediaBackend;
|
||||
|
||||
try {
|
||||
resolve(
|
||||
encode(
|
||||
new Uint8ClampedArray(buffer),
|
||||
metadata?.width ?? 0,
|
||||
metadata?.height ?? 0,
|
||||
4,
|
||||
4,
|
||||
) as string,
|
||||
);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
}))();
|
||||
});
|
||||
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");
|
||||
}
|
||||
|
||||
let url = "";
|
||||
const { path } = await mediaManager.addFile(file);
|
||||
|
||||
let mediaManager: MediaBackend;
|
||||
url = getUrl(path, config);
|
||||
|
||||
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");
|
||||
}
|
||||
let thumbnailUrl = "";
|
||||
|
||||
const { path } = await mediaManager.addFile(file);
|
||||
if (thumbnail) {
|
||||
const { path } = await mediaManager.addFile(thumbnail);
|
||||
|
||||
url = getUrl(path, config);
|
||||
thumbnailUrl = getUrl(path, config);
|
||||
}
|
||||
|
||||
let thumbnailUrl = "";
|
||||
const newAttachment = (
|
||||
await db
|
||||
.insert(Attachments)
|
||||
.values({
|
||||
url,
|
||||
thumbnailUrl,
|
||||
sha256: sha256
|
||||
.update(await file.arrayBuffer())
|
||||
.digest("hex"),
|
||||
mimeType: file.type,
|
||||
description: description ?? "",
|
||||
size: file.size,
|
||||
blurhash: blurhash ?? undefined,
|
||||
width: metadata?.width ?? undefined,
|
||||
height: metadata?.height ?? undefined,
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
// TODO: Add job to process videos and other media
|
||||
|
||||
if (thumbnail) {
|
||||
const { path } = await mediaManager.addFile(thumbnail);
|
||||
|
||||
thumbnailUrl = getUrl(path, config);
|
||||
}
|
||||
|
||||
const newAttachment = (
|
||||
await db
|
||||
.insert(Attachments)
|
||||
.values({
|
||||
url,
|
||||
thumbnailUrl,
|
||||
sha256: sha256
|
||||
.update(await file.arrayBuffer())
|
||||
.digest("hex"),
|
||||
mimeType: file.type,
|
||||
description: description ?? "",
|
||||
size: file.size,
|
||||
blurhash: blurhash ?? undefined,
|
||||
width: metadata?.width ?? undefined,
|
||||
height: metadata?.height ?? undefined,
|
||||
})
|
||||
.returning()
|
||||
)[0];
|
||||
// TODO: Add job to process videos and other media
|
||||
|
||||
return jsonResponse(attachmentToAPI(newAttachment));
|
||||
},
|
||||
);
|
||||
return jsonResponse(attachmentToAPI(newAttachment));
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -26,7 +26,9 @@ beforeAll(async () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
@ -81,7 +83,9 @@ describe(meta.route, () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
|
|
@ -18,31 +20,45 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
const { max_id, since_id, limit, min_id } = extraData.parsedRequest;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { max_id, since_id, limit, min_id } =
|
||||
context.req.valid("query");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { objects: mutes, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${user.id} AND "Relationships"."muting" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
);
|
||||
const { objects: mutes, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${user.id} AND "Relationships"."muting" = true)`,
|
||||
),
|
||||
limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(mutes.map((u) => u.toAPI()));
|
||||
},
|
||||
);
|
||||
return jsonResponse(
|
||||
mutes.map((u) => u.toAPI()),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -15,23 +15,29 @@ let notifications: APINotification[] = [];
|
|||
|
||||
// Create some test notifications: follow, favourite, reblog, mention
|
||||
beforeAll(async () => {
|
||||
await fetch(
|
||||
new URL(`/api/v1/accounts/${users[0].id}/follow`, config.http.base_url),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/accounts/${users[0].id}/follow`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
notifications = await fetch(
|
||||
new URL("/api/v1/notifications", config.http.base_url),
|
||||
{
|
||||
notifications = await sendTestRequest(
|
||||
new Request(new URL("/api/v1/notifications", config.http.base_url), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).then((r) => r.json());
|
||||
|
||||
expect(notifications.length).toBe(1);
|
||||
|
|
@ -45,9 +51,15 @@ afterAll(async () => {
|
|||
describe(meta.route, () => {
|
||||
test("should return 401 if not authenticated", async () => {
|
||||
const response = await sendTestRequest(
|
||||
new Request(new URL(meta.route, config.http.base_url), {
|
||||
method: "POST",
|
||||
}),
|
||||
new Request(
|
||||
new URL(
|
||||
meta.route.replace(":id", notifications[0].id),
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
50
server/api/api/v1/notifications/:id/dismiss.ts
Normal file
50
server/api/api/v1/notifications/:id/dismiss.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Notifications } from "~drizzle/schema";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
route: "/api/v1/notifications/:id/dismiss",
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:notifications"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
|
||||
const { user } = context.req.valid("header");
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
await db
|
||||
.update(Notifications)
|
||||
.set({
|
||||
dismissed: true,
|
||||
})
|
||||
.where(eq(Notifications.id, id));
|
||||
|
||||
return jsonResponse({});
|
||||
},
|
||||
);
|
||||
|
|
@ -15,23 +15,29 @@ let notifications: APINotification[] = [];
|
|||
|
||||
// Create some test notifications: follow, favourite, reblog, mention
|
||||
beforeAll(async () => {
|
||||
await fetch(
|
||||
new URL(`/api/v1/accounts/${users[0].id}/follow`, config.http.base_url),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/accounts/${users[0].id}/follow`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
notifications = await fetch(
|
||||
new URL("/api/v1/notifications", config.http.base_url),
|
||||
{
|
||||
notifications = await sendTestRequest(
|
||||
new Request(new URL("/api/v1/notifications", config.http.base_url), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).then((r) => r.json());
|
||||
|
||||
expect(notifications.length).toBe(1);
|
||||
|
|
@ -45,13 +51,21 @@ afterAll(async () => {
|
|||
describe(meta.route, () => {
|
||||
test("should return 401 if not authenticated", async () => {
|
||||
const response = await sendTestRequest(
|
||||
new Request(new URL(meta.route, config.http.base_url)),
|
||||
new Request(
|
||||
new URL(
|
||||
meta.route.replace(
|
||||
":id",
|
||||
"00000000-0000-0000-0000-000000000000",
|
||||
),
|
||||
config.http.base_url,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
test("should return 404 if ID is invalid", async () => {
|
||||
test("should return 422 if ID is invalid", async () => {
|
||||
const response = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
|
|
@ -65,7 +79,7 @@ describe(meta.route, () => {
|
|||
},
|
||||
),
|
||||
);
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.status).toBe(422);
|
||||
});
|
||||
|
||||
test("should return 404 if notification not found", async () => {
|
||||
51
server/api/api/v1/notifications/:id/index.ts
Normal file
51
server/api/api/v1/notifications/:id/index.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { findManyNotifications } from "~database/entities/Notification";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
route: "/api/v1/notifications/:id",
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["read:notifications"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
|
||||
const { user } = context.req.valid("header");
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const notification = (
|
||||
await findManyNotifications({
|
||||
where: (notification, { eq }) => eq(notification.id, id),
|
||||
limit: 1,
|
||||
})
|
||||
)[0];
|
||||
|
||||
if (!notification)
|
||||
return errorResponse("Notification not found", 404);
|
||||
|
||||
return jsonResponse(notification);
|
||||
},
|
||||
);
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Notifications } from "~drizzle/schema";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
route: "/api/v1/notifications/:id/dismiss",
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["write:notifications"],
|
||||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user } = extraData.auth;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
await db
|
||||
.update(Notifications)
|
||||
.set({
|
||||
dismissed: true,
|
||||
})
|
||||
.where(eq(Notifications.id, id));
|
||||
|
||||
return jsonResponse({});
|
||||
});
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { findManyNotifications } from "~database/entities/Notification";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
route: "/api/v1/notifications/:id",
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
auth: {
|
||||
required: true,
|
||||
oauthPermissions: ["read:notifications"],
|
||||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const id = matchedRoute.params.id;
|
||||
if (!id.match(idValidator)) {
|
||||
return errorResponse("Invalid ID, must be of type UUIDv7", 404);
|
||||
}
|
||||
|
||||
const { user } = extraData.auth;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const notification = (
|
||||
await findManyNotifications({
|
||||
where: (notification, { eq }) => eq(notification.id, id),
|
||||
limit: 1,
|
||||
})
|
||||
)[0];
|
||||
|
||||
if (!notification) return errorResponse("Notification not found", 404);
|
||||
|
||||
return jsonResponse(notification);
|
||||
});
|
||||
|
|
@ -15,23 +15,29 @@ let notifications: APINotification[] = [];
|
|||
|
||||
// Create some test notifications: follow, favourite, reblog, mention
|
||||
beforeAll(async () => {
|
||||
await fetch(
|
||||
new URL(`/api/v1/accounts/${users[0].id}/follow`, config.http.base_url),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/accounts/${users[0].id}/follow`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
notifications = await fetch(
|
||||
new URL("/api/v1/notifications", config.http.base_url),
|
||||
{
|
||||
notifications = await sendTestRequest(
|
||||
new Request(new URL("/api/v1/notifications", config.http.base_url), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).then((r) => r.json());
|
||||
|
||||
expect(notifications.length).toBe(1);
|
||||
|
|
@ -65,13 +71,15 @@ describe(meta.route, () => {
|
|||
|
||||
expect(response.status).toBe(200);
|
||||
|
||||
const newNotifications = await fetch(
|
||||
new URL("/api/v1/notifications", config.http.base_url),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
const newNotifications = await sendTestRequest(
|
||||
new Request(
|
||||
new URL("/api/v1/notifications", config.http.base_url),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
),
|
||||
).then((r) => r.json());
|
||||
|
||||
expect(newNotifications.length).toBe(0);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Notifications } from "~drizzle/schema";
|
||||
|
||||
|
|
@ -17,16 +18,22 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user } = context.req.valid("header");
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
await db
|
||||
.update(Notifications)
|
||||
.set({
|
||||
dismissed: true,
|
||||
})
|
||||
.where(eq(Notifications.notifiedId, user.id));
|
||||
await db
|
||||
.update(Notifications)
|
||||
.set({
|
||||
dismissed: true,
|
||||
})
|
||||
.where(eq(Notifications.notifiedId, user.id));
|
||||
|
||||
return jsonResponse({});
|
||||
});
|
||||
return jsonResponse({});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -17,38 +17,48 @@ let notifications: APINotification[] = [];
|
|||
|
||||
// Create some test notifications
|
||||
beforeAll(async () => {
|
||||
await fetch(
|
||||
new URL(`/api/v1/accounts/${users[0].id}/follow`, config.http.base_url),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
for (const i of [0, 1, 2, 3]) {
|
||||
await fetch(
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${statuses[i].id}/favourite`,
|
||||
`/api/v1/accounts/${users[0].id}/follow`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
for (const i of [0, 1, 2, 3]) {
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${statuses[i].id}/favourite`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
notifications = await fetch(
|
||||
new URL("/api/v1/notifications", config.http.base_url),
|
||||
{
|
||||
notifications = await sendTestRequest(
|
||||
new Request(new URL("/api/v1/notifications", config.http.base_url), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).then((r) => r.json());
|
||||
|
||||
expect(notifications.length).toBe(5);
|
||||
|
|
@ -62,9 +72,17 @@ afterAll(async () => {
|
|||
describe(meta.route, () => {
|
||||
test("should return 401 if not authenticated", async () => {
|
||||
const response = await sendTestRequest(
|
||||
new Request(new URL(meta.route, config.http.base_url), {
|
||||
method: "DELETE",
|
||||
}),
|
||||
new Request(
|
||||
new URL(
|
||||
`${meta.route}?${new URLSearchParams(
|
||||
notifications.slice(1).map((n) => ["ids[]", n.id]),
|
||||
).toString()}`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "DELETE",
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { inArray } from "drizzle-orm";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Notifications } from "~drizzle/schema";
|
||||
|
|
@ -18,24 +20,37 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
ids: z.array(z.string().regex(idValidator)),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
"ids[]": z.array(z.string().uuid()),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
const { ids } = extraData.parsedRequest;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
await db
|
||||
.update(Notifications)
|
||||
.set({
|
||||
dismissed: true,
|
||||
})
|
||||
.where(inArray(Notifications.id, ids));
|
||||
const { "ids[]": ids } = context.req.valid("query");
|
||||
|
||||
return jsonResponse({});
|
||||
},
|
||||
);
|
||||
await db
|
||||
.update(Notifications)
|
||||
.set({
|
||||
dismissed: true,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
inArray(Notifications.id, ids),
|
||||
eq(Notifications.notifiedId, user.id),
|
||||
),
|
||||
);
|
||||
|
||||
return jsonResponse({});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -11,58 +11,87 @@ import { meta } from "./index";
|
|||
|
||||
await deleteOldTestUsers();
|
||||
|
||||
const getFormData = (object: Record<string, string | number | boolean>) =>
|
||||
Object.keys(object).reduce((formData, key) => {
|
||||
formData.append(key, String(object[key]));
|
||||
return formData;
|
||||
}, new FormData());
|
||||
|
||||
const { users, tokens, deleteUsers } = await getTestUsers(2);
|
||||
const timeline = (await getTestStatuses(40, users[0])).toReversed();
|
||||
// Create some test notifications: follow, favourite, reblog, mention
|
||||
beforeAll(async () => {
|
||||
await fetch(
|
||||
new URL(`/api/v1/accounts/${users[0].id}/follow`, config.http.base_url),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
const res1 = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/accounts/${users[0].id}/follow`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await fetch(
|
||||
new URL(
|
||||
`/api/v1/statuses/${timeline[0].id}/favourite`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await fetch(
|
||||
new URL(
|
||||
`/api/v1/statuses/${timeline[0].id}/reblog`,
|
||||
config.http.base_url,
|
||||
expect(res1.status).toBe(200);
|
||||
|
||||
const res2 = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${timeline[0].id}/favourite`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
{
|
||||
);
|
||||
|
||||
expect(res2.status).toBe(200);
|
||||
|
||||
const res3 = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${timeline[0].id}/reblog`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
},
|
||||
body: getFormData({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
expect(res3.status).toBe(200);
|
||||
|
||||
const res4 = await sendTestRequest(
|
||||
new Request(new URL("/api/v1/statuses", config.http.base_url), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await fetch(new URL("/api/v1/statuses", config.http.base_url), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
status: `@${users[0].getUser().username} test mention`,
|
||||
visibility: "direct",
|
||||
federate: false,
|
||||
body: getFormData({
|
||||
status: `@${users[0].getUser().username} test mention`,
|
||||
visibility: "direct",
|
||||
federate: false,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
);
|
||||
|
||||
expect(res4.status).toBe(200);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
|
|
@ -109,24 +138,21 @@ describe(meta.route, () => {
|
|||
});
|
||||
|
||||
test("should not return notifications with filtered keywords", async () => {
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append("title", "Test Filter");
|
||||
formData.append("context[]", "notifications");
|
||||
formData.append("filter_action", "hide");
|
||||
formData.append(
|
||||
"keywords_attributes[0][keyword]",
|
||||
timeline[0].content.slice(4, 20),
|
||||
);
|
||||
formData.append("keywords_attributes[0][whole_word]", "false");
|
||||
|
||||
const filterResponse = await sendTestRequest(
|
||||
new Request(new URL("/api/v2/filters", config.http.base_url), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[0].accessToken}`,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: formData,
|
||||
body: new URLSearchParams({
|
||||
title: "Test Filter",
|
||||
"context[]": "notifications",
|
||||
filter_action: "hide",
|
||||
"keywords_attributes[0][keyword]":
|
||||
timeline[0].content.slice(4, 20),
|
||||
"keywords_attributes[0][whole_word]": "false",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { apiRoute, applyConfig, idValidator } from "@api";
|
||||
import { apiRoute, applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { fetchTimeline } from "@timelines";
|
||||
import { sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
findManyNotifications,
|
||||
|
|
@ -22,144 +24,164 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).optional().default(15),
|
||||
exclude_types: z
|
||||
.enum([
|
||||
"mention",
|
||||
"status",
|
||||
"follow",
|
||||
"follow_request",
|
||||
"reblog",
|
||||
"poll",
|
||||
"favourite",
|
||||
"update",
|
||||
"admin.sign_up",
|
||||
"admin.report",
|
||||
"chat",
|
||||
"pleroma:chat_mention",
|
||||
"pleroma:emoji_reaction",
|
||||
"pleroma:event_reminder",
|
||||
"pleroma:participation_request",
|
||||
"pleroma:participation_accepted",
|
||||
"move",
|
||||
"group_reblog",
|
||||
"group_favourite",
|
||||
"user_approved",
|
||||
])
|
||||
.array()
|
||||
.optional(),
|
||||
types: z
|
||||
.enum([
|
||||
"mention",
|
||||
"status",
|
||||
"follow",
|
||||
"follow_request",
|
||||
"reblog",
|
||||
"poll",
|
||||
"favourite",
|
||||
"update",
|
||||
"admin.sign_up",
|
||||
"admin.report",
|
||||
"chat",
|
||||
"pleroma:chat_mention",
|
||||
"pleroma:emoji_reaction",
|
||||
"pleroma:event_reminder",
|
||||
"pleroma:participation_request",
|
||||
"pleroma:participation_accepted",
|
||||
"move",
|
||||
"group_reblog",
|
||||
"group_favourite",
|
||||
"user_approved",
|
||||
])
|
||||
.array()
|
||||
.optional(),
|
||||
account_id: z.string().regex(idValidator).optional(),
|
||||
});
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(15),
|
||||
exclude_types: z
|
||||
.enum([
|
||||
"mention",
|
||||
"status",
|
||||
"follow",
|
||||
"follow_request",
|
||||
"reblog",
|
||||
"poll",
|
||||
"favourite",
|
||||
"update",
|
||||
"admin.sign_up",
|
||||
"admin.report",
|
||||
"chat",
|
||||
"pleroma:chat_mention",
|
||||
"pleroma:emoji_reaction",
|
||||
"pleroma:event_reminder",
|
||||
"pleroma:participation_request",
|
||||
"pleroma:participation_accepted",
|
||||
"move",
|
||||
"group_reblog",
|
||||
"group_favourite",
|
||||
"user_approved",
|
||||
])
|
||||
.array()
|
||||
.optional(),
|
||||
types: z
|
||||
.enum([
|
||||
"mention",
|
||||
"status",
|
||||
"follow",
|
||||
"follow_request",
|
||||
"reblog",
|
||||
"poll",
|
||||
"favourite",
|
||||
"update",
|
||||
"admin.sign_up",
|
||||
"admin.report",
|
||||
"chat",
|
||||
"pleroma:chat_mention",
|
||||
"pleroma:emoji_reaction",
|
||||
"pleroma:event_reminder",
|
||||
"pleroma:participation_request",
|
||||
"pleroma:participation_accepted",
|
||||
"move",
|
||||
"group_reblog",
|
||||
"group_favourite",
|
||||
"user_approved",
|
||||
])
|
||||
.array()
|
||||
.optional(),
|
||||
account_id: z.string().regex(idValidator).optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user } = context.req.valid("header");
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
const {
|
||||
account_id,
|
||||
exclude_types,
|
||||
limit,
|
||||
max_id,
|
||||
min_id,
|
||||
since_id,
|
||||
types,
|
||||
} = context.req.valid("query");
|
||||
|
||||
const {
|
||||
account_id,
|
||||
exclude_types,
|
||||
limit,
|
||||
max_id,
|
||||
min_id,
|
||||
since_id,
|
||||
types,
|
||||
} = extraData.parsedRequest;
|
||||
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, link } =
|
||||
await fetchTimeline<NotificationWithRelations>(
|
||||
findManyNotifications,
|
||||
{
|
||||
where: (
|
||||
// @ts-expect-error Yes I KNOW the types are wrong
|
||||
notification,
|
||||
// @ts-expect-error Yes I KNOW the types are wrong
|
||||
{ lt, gte, gt, and, eq, not, inArray },
|
||||
) =>
|
||||
and(
|
||||
max_id ? lt(notification.id, max_id) : undefined,
|
||||
since_id
|
||||
? gte(notification.id, since_id)
|
||||
: undefined,
|
||||
min_id ? gt(notification.id, min_id) : undefined,
|
||||
eq(notification.notifiedId, user.id),
|
||||
eq(notification.dismissed, false),
|
||||
account_id
|
||||
? eq(notification.accountId, account_id)
|
||||
: undefined,
|
||||
not(eq(notification.accountId, user.id)),
|
||||
types
|
||||
? inArray(notification.type, types)
|
||||
: undefined,
|
||||
exclude_types
|
||||
? not(inArray(notification.type, exclude_types))
|
||||
: undefined,
|
||||
// Don't show notes that have filtered words in them (via Notification.note.content via Notification.noteId)
|
||||
// Filters in `Filters` table have keyword in `FilterKeywords` table (use LIKE)
|
||||
// Filters table has a userId and a context which is an array
|
||||
sql`NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "Filters"
|
||||
WHERE "Filters"."userId" = ${user.id}
|
||||
AND "Filters"."filter_action" = 'hide'
|
||||
AND EXISTS (
|
||||
const { objects, link } =
|
||||
await fetchTimeline<NotificationWithRelations>(
|
||||
findManyNotifications,
|
||||
{
|
||||
where: (
|
||||
// @ts-expect-error Yes I KNOW the types are wrong
|
||||
notification,
|
||||
// @ts-expect-error Yes I KNOW the types are wrong
|
||||
{ lt, gte, gt, and, eq, not, inArray },
|
||||
) =>
|
||||
and(
|
||||
max_id
|
||||
? lt(notification.id, max_id)
|
||||
: undefined,
|
||||
since_id
|
||||
? gte(notification.id, since_id)
|
||||
: undefined,
|
||||
min_id
|
||||
? gt(notification.id, min_id)
|
||||
: undefined,
|
||||
eq(notification.notifiedId, user.id),
|
||||
eq(notification.dismissed, false),
|
||||
account_id
|
||||
? eq(notification.accountId, account_id)
|
||||
: undefined,
|
||||
not(eq(notification.accountId, user.id)),
|
||||
types
|
||||
? inArray(notification.type, types)
|
||||
: undefined,
|
||||
exclude_types
|
||||
? not(
|
||||
inArray(
|
||||
notification.type,
|
||||
exclude_types,
|
||||
),
|
||||
)
|
||||
: undefined,
|
||||
// Don't show notes that have filtered words in them (via Notification.note.content via Notification.noteId)
|
||||
// Filters in `Filters` table have keyword in `FilterKeywords` table (use LIKE)
|
||||
// Filters table has a userId and a context which is an array
|
||||
sql`NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "FilterKeywords", "Notifications" as "n_inner", "Notes"
|
||||
WHERE "FilterKeywords"."filterId" = "Filters"."id"
|
||||
AND "n_inner"."noteId" = "Notes"."id"
|
||||
AND "Notes"."content" LIKE '%' || "FilterKeywords"."keyword" || '%'
|
||||
AND "n_inner"."id" = "Notifications"."id"
|
||||
)
|
||||
AND "Filters"."context" @> ARRAY['notifications']
|
||||
)`,
|
||||
),
|
||||
limit,
|
||||
// @ts-expect-error Yes I KNOW the types are wrong
|
||||
orderBy: (notification, { desc }) => desc(notification.id),
|
||||
},
|
||||
req,
|
||||
);
|
||||
FROM "Filters"
|
||||
WHERE "Filters"."userId" = ${user.id}
|
||||
AND "Filters"."filter_action" = 'hide'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM "FilterKeywords", "Notifications" as "n_inner", "Notes"
|
||||
WHERE "FilterKeywords"."filterId" = "Filters"."id"
|
||||
AND "n_inner"."noteId" = "Notes"."id"
|
||||
AND "Notes"."content" LIKE
|
||||
'%' || "FilterKeywords"."keyword" || '%'
|
||||
AND "n_inner"."id" = "Notifications"."id"
|
||||
)
|
||||
AND "Filters"."context" @> ARRAY['notifications']
|
||||
)`,
|
||||
),
|
||||
limit,
|
||||
// @ts-expect-error Yes I KNOW the types are wrong
|
||||
orderBy: (notification, { desc }) =>
|
||||
desc(notification.id),
|
||||
},
|
||||
context.req.raw,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((n) => notificationToAPI(n))),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map((n) => notificationToAPI(n))),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
|
@ -17,18 +18,24 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Deletes a user avatar
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const { user: self } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
await db.update(Users).set({ avatar: "" }).where(eq(Users.id, self.id));
|
||||
await db
|
||||
.update(Users)
|
||||
.set({ avatar: "" })
|
||||
.where(eq(Users.id, self.id));
|
||||
|
||||
return jsonResponse({
|
||||
...(await User.fromId(self.id))?.toAPI(),
|
||||
avatar: "",
|
||||
});
|
||||
});
|
||||
return jsonResponse({
|
||||
...(await User.fromId(self.id))?.toAPI(),
|
||||
avatar: "",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { apiRoute, applyConfig } from "@api";
|
||||
import { applyConfig, auth } from "@api";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { User } from "~packages/database-interface/user";
|
||||
|
|
@ -17,19 +18,24 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Deletes a user header
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const { user: self } = extraData.auth;
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
if (!self) return errorResponse("Unauthorized", 401);
|
||||
|
||||
// Delete user header
|
||||
await db.update(Users).set({ header: "" }).where(eq(Users.id, self.id));
|
||||
await db
|
||||
.update(Users)
|
||||
.set({ header: "" })
|
||||
.where(eq(Users.id, self.id));
|
||||
|
||||
return jsonResponse({
|
||||
...(await User.fromId(self.id))?.toAPI(),
|
||||
header: "",
|
||||
});
|
||||
});
|
||||
return jsonResponse({
|
||||
...(await User.fromId(self.id))?.toAPI(),
|
||||
header: "",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
54
server/api/api/v1/statuses/:id/context.ts
Normal file
54
server/api/api/v1/statuses/:id/context.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 8,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/statuses/:id/context",
|
||||
auth: {
|
||||
required: false,
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
const foundStatus = await Note.fromId(id);
|
||||
|
||||
if (!foundStatus) return errorResponse("Record not found", 404);
|
||||
|
||||
const ancestors = await foundStatus.getAncestors(user ?? null);
|
||||
|
||||
const descendants = await foundStatus.getDescendants(user ?? null);
|
||||
|
||||
return jsonResponse({
|
||||
ancestors: await Promise.all(
|
||||
ancestors.map((status) => status.toAPI(user)),
|
||||
),
|
||||
descendants: await Promise.all(
|
||||
descendants.map((status) => status.toAPI(user)),
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
65
server/api/api/v1/statuses/:id/favourite.ts
Normal file
65
server/api/api/v1/statuses/:id/favourite.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { createLike } from "~database/entities/Like";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
import type { Status as APIStatus } from "~types/mastodon/status";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/statuses/:id/favourite",
|
||||
auth: {
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const note = await Note.fromId(id);
|
||||
|
||||
if (!note?.isViewableByUser(user))
|
||||
return errorResponse("Record not found", 404);
|
||||
|
||||
const existingLike = await db.query.Likes.findFirst({
|
||||
where: (like, { and, eq }) =>
|
||||
and(
|
||||
eq(like.likedId, note.getStatus().id),
|
||||
eq(like.likerId, user.id),
|
||||
),
|
||||
});
|
||||
|
||||
if (!existingLike) {
|
||||
await createLike(user, note);
|
||||
}
|
||||
|
||||
return jsonResponse({
|
||||
...(await note.toAPI(user)),
|
||||
favourited: true,
|
||||
favourites_count: note.getStatus().likeCount + 1,
|
||||
} as APIStatus);
|
||||
},
|
||||
);
|
||||
|
|
@ -20,17 +20,19 @@ afterAll(async () => {
|
|||
|
||||
beforeAll(async () => {
|
||||
for (const status of timeline) {
|
||||
const res = await fetch(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/favourite`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
const res = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/favourite`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
75
server/api/api/v1/statuses/:id/favourited_by.ts
Normal file
75
server/api/api/v1/statuses/:id/favourited_by.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, gt, gte, lt, sql } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { Users } from "~drizzle/schema";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
import { Timeline } from "~packages/database-interface/timeline";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET"],
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/statuses/:id/favourited_by",
|
||||
auth: {
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
max_id: z.string().regex(idValidator).optional(),
|
||||
since_id: z.string().regex(idValidator).optional(),
|
||||
min_id: z.string().regex(idValidator).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(40),
|
||||
}),
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { max_id, since_id, min_id, limit } =
|
||||
context.req.valid("query");
|
||||
const { id } = context.req.valid("param");
|
||||
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const status = await Note.fromId(id);
|
||||
|
||||
if (!status?.isViewableByUser(user))
|
||||
return errorResponse("Record not found", 404);
|
||||
|
||||
const { objects, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
min_id ? gt(Users.id, min_id) : undefined,
|
||||
sql`EXISTS (SELECT 1 FROM "Likes" WHERE "Likes"."likedId" = ${status.id} AND "Likes"."likerId" = ${Users.id})`,
|
||||
),
|
||||
limit,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
objects.map((user) => user.toAPI()),
|
||||
200,
|
||||
{
|
||||
Link: link,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
160
server/api/api/v1/statuses/:id/index.ts
Normal file
160
server/api/api/v1/statuses/:id/index.ts
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { config } from "config-manager";
|
||||
import type { Hono } from "hono";
|
||||
import ISO6391 from "iso-639-1";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["GET", "DELETE", "PUT"],
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/statuses/:id",
|
||||
auth: {
|
||||
required: false,
|
||||
requiredOnMethods: ["DELETE", "PUT"],
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().regex(idValidator),
|
||||
}),
|
||||
form: z.object({
|
||||
status: z.string().max(config.validation.max_note_size).optional(),
|
||||
content_type: z.string().optional().default("text/plain"),
|
||||
media_ids: z
|
||||
.array(z.string().regex(idValidator))
|
||||
.max(config.validation.max_media_attachments)
|
||||
.optional(),
|
||||
spoiler_text: z.string().max(255).optional(),
|
||||
sensitive: z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
language: z
|
||||
.enum(ISO6391.getAllCodes() as [string, ...string[]])
|
||||
.optional(),
|
||||
"poll[options]": z
|
||||
.array(z.string().max(config.validation.max_poll_option_size))
|
||||
.max(config.validation.max_poll_options)
|
||||
.optional(),
|
||||
"poll[expires_in]": z
|
||||
.number()
|
||||
.int()
|
||||
.min(config.validation.min_poll_duration)
|
||||
.max(config.validation.max_poll_duration)
|
||||
.optional(),
|
||||
"poll[multiple]": z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
"poll[hide_totals]": z
|
||||
.string()
|
||||
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
||||
.optional(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
const foundStatus = await Note.fromId(id);
|
||||
|
||||
if (!foundStatus?.isViewableByUser(user))
|
||||
return errorResponse("Record not found", 404);
|
||||
|
||||
if (context.req.method === "GET") {
|
||||
return jsonResponse(await foundStatus.toAPI(user));
|
||||
}
|
||||
if (context.req.method === "DELETE") {
|
||||
if (foundStatus.getAuthor().id !== user?.id) {
|
||||
return errorResponse("Unauthorized", 401);
|
||||
}
|
||||
|
||||
// TODO: Delete and redraft
|
||||
|
||||
await foundStatus.delete();
|
||||
|
||||
return jsonResponse(await foundStatus.toAPI(user), 200);
|
||||
}
|
||||
|
||||
// TODO: Polls
|
||||
const {
|
||||
status: statusText,
|
||||
content_type,
|
||||
"poll[options]": options,
|
||||
media_ids,
|
||||
spoiler_text,
|
||||
sensitive,
|
||||
} = context.req.valid("form");
|
||||
|
||||
if (!statusText && !(media_ids && media_ids.length > 0)) {
|
||||
return errorResponse(
|
||||
"Status is required unless media is attached",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
if (media_ids && media_ids.length > 0 && options) {
|
||||
return errorResponse(
|
||||
"Cannot attach poll to post with media",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
config.filters.note_content.some((filter) =>
|
||||
statusText?.match(filter),
|
||||
)
|
||||
) {
|
||||
return errorResponse("Status contains blocked words", 422);
|
||||
}
|
||||
|
||||
if (media_ids && media_ids.length > 0) {
|
||||
const foundAttachments = await db.query.Attachments.findMany({
|
||||
where: (attachment, { inArray }) =>
|
||||
inArray(attachment.id, media_ids),
|
||||
});
|
||||
|
||||
if (foundAttachments.length !== (media_ids ?? []).length) {
|
||||
return errorResponse("Invalid media IDs", 422);
|
||||
}
|
||||
}
|
||||
|
||||
const newNote = await foundStatus.updateFromData(
|
||||
statusText
|
||||
? {
|
||||
[content_type]: {
|
||||
content: statusText,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
undefined,
|
||||
sensitive,
|
||||
spoiler_text,
|
||||
undefined,
|
||||
undefined,
|
||||
media_ids,
|
||||
);
|
||||
|
||||
if (!newNote) {
|
||||
return errorResponse("Failed to update status", 500);
|
||||
}
|
||||
|
||||
return jsonResponse(await newNote.toAPI(user));
|
||||
},
|
||||
);
|
||||
65
server/api/api/v1/statuses/:id/pin.ts
Normal file
65
server/api/api/v1/statuses/:id/pin.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { applyConfig, auth, handleZodError, idValidator } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/statuses/:id/pin",
|
||||
auth: {
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().regex(idValidator),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const foundStatus = await Note.fromId(id);
|
||||
|
||||
if (!foundStatus) return errorResponse("Record not found", 404);
|
||||
|
||||
if (foundStatus.getAuthor().id !== user.id)
|
||||
return errorResponse("Unauthorized", 401);
|
||||
|
||||
if (
|
||||
await db.query.UserToPinnedNotes.findFirst({
|
||||
where: (userPinnedNote, { and, eq }) =>
|
||||
and(
|
||||
eq(
|
||||
userPinnedNote.noteId,
|
||||
foundStatus.getStatus().id,
|
||||
),
|
||||
eq(userPinnedNote.userId, user.id),
|
||||
),
|
||||
})
|
||||
) {
|
||||
return errorResponse("Already pinned", 422);
|
||||
}
|
||||
|
||||
await user.pin(foundStatus);
|
||||
|
||||
return jsonResponse(await foundStatus.toAPI(user));
|
||||
},
|
||||
);
|
||||
92
server/api/api/v1/statuses/:id/reblog.ts
Normal file
92
server/api/api/v1/statuses/:id/reblog.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { applyConfig, auth, handleZodError } from "@api";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import { db } from "~drizzle/db";
|
||||
import { Notes, Notifications } from "~drizzle/schema";
|
||||
import { Note } from "~packages/database-interface/note";
|
||||
|
||||
export const meta = applyConfig({
|
||||
allowedMethods: ["POST"],
|
||||
ratelimits: {
|
||||
max: 100,
|
||||
duration: 60,
|
||||
},
|
||||
route: "/api/v1/statuses/:id/reblog",
|
||||
auth: {
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
export const schemas = {
|
||||
param: z.object({
|
||||
id: z.string().uuid(),
|
||||
}),
|
||||
form: z.object({
|
||||
visibility: z.enum(["public", "unlisted", "private"]).default("public"),
|
||||
}),
|
||||
};
|
||||
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("param", schemas.param, handleZodError),
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { id } = context.req.valid("param");
|
||||
const { visibility } = context.req.valid("form");
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const foundStatus = await Note.fromId(id);
|
||||
|
||||
if (!foundStatus?.isViewableByUser(user))
|
||||
return errorResponse("Record not found", 404);
|
||||
|
||||
const existingReblog = await Note.fromSql(
|
||||
and(
|
||||
eq(Notes.authorId, user.id),
|
||||
eq(Notes.reblogId, foundStatus.getStatus().id),
|
||||
),
|
||||
);
|
||||
|
||||
if (existingReblog) {
|
||||
return errorResponse("Already reblogged", 422);
|
||||
}
|
||||
|
||||
const newReblog = await Note.insert({
|
||||
authorId: user.id,
|
||||
reblogId: foundStatus.getStatus().id,
|
||||
visibility,
|
||||
sensitive: false,
|
||||
updatedAt: new Date().toISOString(),
|
||||
applicationId: null,
|
||||
});
|
||||
|
||||
if (!newReblog) {
|
||||
return errorResponse("Failed to reblog", 500);
|
||||
}
|
||||
|
||||
const finalNewReblog = await Note.fromId(newReblog.id);
|
||||
|
||||
if (!finalNewReblog) {
|
||||
return errorResponse("Failed to reblog", 500);
|
||||
}
|
||||
|
||||
if (foundStatus.getAuthor().isLocal() && user.isLocal()) {
|
||||
await db.insert(Notifications).values({
|
||||
accountId: user.id,
|
||||
notifiedId: foundStatus.getAuthor().id,
|
||||
type: "reblog",
|
||||
noteId: newReblog.reblogId,
|
||||
});
|
||||
}
|
||||
|
||||
return jsonResponse(await finalNewReblog.toAPI(user));
|
||||
},
|
||||
);
|
||||
|
|
@ -20,17 +20,19 @@ afterAll(async () => {
|
|||
|
||||
beforeAll(async () => {
|
||||
for (const status of timeline) {
|
||||
await fetch(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/reblog`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/reblog`,
|
||||
config.http.base_url,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue