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,9 +15,8 @@ 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, async (context) => {
|
||||
return jsonResponse({
|
||||
http: {
|
||||
bind: config.http.bind,
|
||||
|
|
|
|||
|
|
@ -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,9 +22,12 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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([
|
||||
|
|
@ -48,7 +53,8 @@ export const schema = z.object({
|
|||
.int()
|
||||
.optional()
|
||||
.default(60 * 60 * 24 * 7),
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
const returnError = (query: object, error: string, description: string) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
|
|
@ -66,22 +72,21 @@ 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()));
|
||||
const user = await User.fromSql(
|
||||
eq(Users.email, email.toLowerCase()),
|
||||
);
|
||||
|
||||
if (
|
||||
!user ||
|
||||
|
|
@ -91,13 +96,11 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
))
|
||||
)
|
||||
return returnError(
|
||||
extraData.parsedRequest,
|
||||
context.req.query(),
|
||||
"invalid_request",
|
||||
"Invalid email or password",
|
||||
);
|
||||
|
||||
const { client_id } = extraData.parsedRequest;
|
||||
|
||||
// Try and import the key
|
||||
const privateKey = await crypto.subtle.importKey(
|
||||
"pkcs8",
|
||||
|
|
@ -136,8 +139,12 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
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)
|
||||
for (const [key, value] of Object.entries(context.req.query())) {
|
||||
if (
|
||||
key !== "email" &&
|
||||
key !== "password" &&
|
||||
value !== undefined
|
||||
)
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,30 +23,35 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
user: z.object({
|
||||
email: z.string().email().toLowerCase(),
|
||||
password: z.string().max(100).min(3),
|
||||
password: z.string().min(2).max(100),
|
||||
}),
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Mastodon-FE login route
|
||||
*/
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
async (context) => {
|
||||
const {
|
||||
user: { email, password },
|
||||
} = extraData.parsedRequest;
|
||||
} = context.req.valid("form");
|
||||
|
||||
const redirectToLogin = (error: string) =>
|
||||
Response.redirect(
|
||||
`/auth/sign_in?${new URLSearchParams({
|
||||
...matchedRoute.query,
|
||||
response(null, 302, {
|
||||
Location: `/auth/sign_in?${new URLSearchParams({
|
||||
...context.req.query,
|
||||
error: encodeURIComponent(error),
|
||||
}).toString()}`,
|
||||
302,
|
||||
);
|
||||
});
|
||||
|
||||
const user = await User.fromSql(eq(Users.email, email));
|
||||
|
||||
|
|
@ -72,14 +80,11 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
const maxAge = String(60 * 60 * 24 * 7);
|
||||
|
||||
// Redirect to home
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
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,8 +17,8 @@ export const meta = applyConfig({
|
|||
/**
|
||||
* Mastodon-FE logout route
|
||||
*/
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
// Redirect to home
|
||||
export default (app: Hono) =>
|
||||
app.on(meta.allowedMethods, meta.route, async () => {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
Location: "/",
|
||||
|
|
|
|||
|
|
@ -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,18 +18,30 @@ 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,
|
||||
...context.req.query,
|
||||
error: encodeURIComponent(error),
|
||||
}).toString()}`,
|
||||
302,
|
||||
|
|
@ -35,8 +50,16 @@ export default apiRoute(async (req, matchedRoute) => {
|
|||
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)))
|
||||
.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)
|
||||
|
|
@ -44,4 +67,5 @@ export default apiRoute(async (req, matchedRoute) => {
|
|||
|
||||
// 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,7 +20,8 @@ afterAll(async () => {
|
|||
|
||||
beforeAll(async () => {
|
||||
for (const status of timeline) {
|
||||
await fetch(
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/favourite`,
|
||||
config.http.base_url,
|
||||
|
|
@ -29,8 +30,11 @@ beforeAll(async () => {
|
|||
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,22 +21,26 @@ 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);
|
||||
|
||||
const { id: ids } = extraData.parsedRequest;
|
||||
|
||||
const idFollowerRelationships = await db.query.Relationships.findMany({
|
||||
const idFollowerRelationships =
|
||||
await db.query.Relationships.findMany({
|
||||
columns: {
|
||||
ownerId: true,
|
||||
},
|
||||
|
|
@ -50,7 +56,8 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
}
|
||||
|
||||
// Find users that you follow in idFollowerRelationships
|
||||
const relevantRelationships = await db.query.Relationships.findMany({
|
||||
const relevantRelationships = await db.query.Relationships.findMany(
|
||||
{
|
||||
columns: {
|
||||
subjectId: true,
|
||||
},
|
||||
|
|
@ -63,7 +70,8 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
),
|
||||
eq(relationship.following, true),
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
if (relevantRelationships.length === 0) {
|
||||
return jsonResponse([]);
|
||||
|
|
|
|||
|
|
@ -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,23 +23,28 @@ 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(),
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
username: z.string(),
|
||||
email: z.string(),
|
||||
password: z.string(),
|
||||
agreement: z.boolean(),
|
||||
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
|
||||
|
||||
const body = extraData.parsedRequest;
|
||||
|
||||
const config = await extraData.configManager.getConfig();
|
||||
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");
|
||||
|
||||
if (!config.signups.registration) {
|
||||
return jsonResponse(
|
||||
|
|
@ -85,7 +93,7 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
"reason",
|
||||
]) {
|
||||
// @ts-expect-error We don't care about typing here
|
||||
if (!body[value]) {
|
||||
if (!parsedRequest[value]) {
|
||||
errors.details[value].push({
|
||||
error: "ERR_BLANK",
|
||||
description: `can't be blank`,
|
||||
|
|
@ -94,7 +102,7 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
}
|
||||
|
||||
// Check if username is valid
|
||||
if (!body.username?.match(/^[a-z0-9_]+$/))
|
||||
if (!username?.match(/^[a-z0-9_]+$/))
|
||||
errors.details.username.push({
|
||||
error: "ERR_INVALID",
|
||||
description:
|
||||
|
|
@ -104,7 +112,7 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
// Check if username doesnt match filters
|
||||
if (
|
||||
config.filters.username.some((filter) =>
|
||||
body.username?.match(filter),
|
||||
username?.match(filter),
|
||||
)
|
||||
) {
|
||||
errors.details.username.push({
|
||||
|
|
@ -114,28 +122,28 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
}
|
||||
|
||||
// Check if username is too long
|
||||
if ((body.username?.length ?? 0) > config.validation.max_username_size)
|
||||
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 ((body.username?.length ?? 0) < 3)
|
||||
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(body.username ?? ""))
|
||||
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, body.username))) {
|
||||
if (await User.fromSql(eq(Users.username, username))) {
|
||||
errors.details.username.push({
|
||||
error: "ERR_TAKEN",
|
||||
description: "is already taken",
|
||||
|
|
@ -144,7 +152,7 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
|
||||
// Check if email is valid
|
||||
if (
|
||||
!body.email?.match(
|
||||
!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,}))$/,
|
||||
)
|
||||
)
|
||||
|
|
@ -155,10 +163,10 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
|
||||
// Check if email is blocked
|
||||
if (
|
||||
config.validation.email_blacklist.includes(body.email ?? "") ||
|
||||
config.validation.email_blacklist.includes(email) ||
|
||||
(config.validation.blacklist_tempmail &&
|
||||
tempmailDomains.domains.includes(
|
||||
(body.email ?? "").split("@")[1],
|
||||
(email ?? "").split("@")[1],
|
||||
))
|
||||
)
|
||||
errors.details.email.push({
|
||||
|
|
@ -167,33 +175,35 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
});
|
||||
|
||||
// Check if email is taken
|
||||
if (await User.fromSql(eq(Users.email, body.email)))
|
||||
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 (!body.agreement)
|
||||
if (!agreement)
|
||||
errors.details.agreement.push({
|
||||
error: "ERR_ACCEPTED",
|
||||
description: "must be accepted",
|
||||
});
|
||||
|
||||
if (!body.locale)
|
||||
if (!locale)
|
||||
errors.details.locale.push({
|
||||
error: "ERR_BLANK",
|
||||
description: `can't be blank`,
|
||||
});
|
||||
|
||||
if (!ISO6391.validate(body.locale ?? ""))
|
||||
if (!ISO6391.validate(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)) {
|
||||
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)
|
||||
|
|
@ -219,9 +229,9 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
}
|
||||
|
||||
await User.fromDataLocal({
|
||||
username: body.username ?? "",
|
||||
password: body.password ?? "",
|
||||
email: body.email ?? "",
|
||||
username: username ?? "",
|
||||
password: password ?? "",
|
||||
email: email ?? "",
|
||||
});
|
||||
|
||||
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,13 +34,20 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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);
|
||||
|
|
@ -67,16 +76,17 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
}
|
||||
|
||||
const [username, domain] = accountMatches[0].split("@");
|
||||
const foundAccount = await resolveWebFinger(username, domain).catch(
|
||||
(e) => {
|
||||
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());
|
||||
|
|
|
|||
|
|
@ -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,21 +23,24 @@ 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);
|
||||
|
||||
const { id: ids } = extraData.parsedRequest;
|
||||
|
||||
const relationships = await db.query.Relationships.findMany({
|
||||
where: (relationship, { inArray, and, eq }) =>
|
||||
and(
|
||||
|
|
@ -44,21 +49,18 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
),
|
||||
});
|
||||
|
||||
// Find IDs that dont have a relationship
|
||||
const missingIds = ids.filter(
|
||||
(id) => !relationships.some((r) => r.subjectId === id),
|
||||
);
|
||||
|
||||
// Create the missing relationships
|
||||
for (const id of missingIds) {
|
||||
const relationship = await createNewRelationship(self, {
|
||||
id,
|
||||
} as UserType);
|
||||
const user = await User.fromId(id);
|
||||
if (!user) continue;
|
||||
const relationship = await createNewRelationship(self, user);
|
||||
|
||||
relationships.push(relationship);
|
||||
}
|
||||
|
||||
// Order in the same order as ids
|
||||
relationships.sort(
|
||||
(a, b) => ids.indexOf(a.subjectId) - ids.indexOf(b.subjectId),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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,7 +33,8 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
export const schemas = {
|
||||
query: z.object({
|
||||
q: z
|
||||
.string()
|
||||
.min(1)
|
||||
|
|
@ -44,35 +47,39 @@ export const schema = z.object({
|
|||
).groupedAs("username"),
|
||||
maybe(
|
||||
exactly("@"),
|
||||
oneOrMore(anyOf(letter, digit, charIn("_-.:"))).groupedAs(
|
||||
"domain",
|
||||
),
|
||||
oneOrMore(
|
||||
anyOf(letter, digit, charIn("_-.:")),
|
||||
).groupedAs("domain"),
|
||||
),
|
||||
[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(),
|
||||
});
|
||||
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;
|
||||
|
||||
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 { q, limit, offset, resolve, following } =
|
||||
context.req.valid("query");
|
||||
const { user: self } = context.req.valid("header");
|
||||
|
||||
if (!self && following) return errorResponse("Unauthorized", 401);
|
||||
|
||||
// Remove any leading @
|
||||
const [username, host] = q.replace(/^@/, "").split("@");
|
||||
|
||||
const accounts: User[] = [];
|
||||
|
|
@ -101,8 +108,6 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
);
|
||||
}
|
||||
|
||||
// Sort accounts by closest match
|
||||
// Returns array of numbers (indexes of accounts array)
|
||||
const indexOfCorrectSort = stringComparison.jaccardIndex
|
||||
.sortMatch(
|
||||
q,
|
||||
|
|
|
|||
|
|
@ -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,7 +30,8 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
display_name: z
|
||||
.string()
|
||||
.min(3)
|
||||
|
|
@ -43,15 +46,29 @@ export const schema = z.object({
|
|||
.optional(),
|
||||
avatar: z.instanceof(File).optional(),
|
||||
header: z.instanceof(File).optional(),
|
||||
locked: z.boolean().optional(),
|
||||
bot: z.boolean().optional(),
|
||||
discoverable: z.boolean().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.boolean().optional(),
|
||||
sensitive: z
|
||||
.string()
|
||||
.transform((v) =>
|
||||
["true", "1", "on"].includes(v.toLowerCase()),
|
||||
)
|
||||
.optional(),
|
||||
language: z
|
||||
.enum(ISO6391.getAllCodes() as [string, ...string[]])
|
||||
.optional(),
|
||||
|
|
@ -72,17 +89,17 @@ export const schema = z.object({
|
|||
)
|
||||
.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();
|
||||
}),
|
||||
};
|
||||
|
||||
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,
|
||||
|
|
@ -93,7 +110,11 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
discoverable,
|
||||
source,
|
||||
fields_attributes,
|
||||
} = extraData.parsedRequest;
|
||||
} = context.req.valid("form");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const self = user.getUser();
|
||||
|
||||
const sanitizedNote = await sanitizeHtml(note ?? "");
|
||||
|
||||
|
|
@ -134,7 +155,9 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
if (note && self.source) {
|
||||
// Check if bio doesnt match filters
|
||||
if (
|
||||
config.filters.bio.some((filter) => sanitizedNote.match(filter))
|
||||
config.filters.bio.some((filter) =>
|
||||
sanitizedNote.match(filter),
|
||||
)
|
||||
) {
|
||||
return errorResponse("Bio contains blocked words", 422);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
const { user } = extraData.auth;
|
||||
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");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
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,20 +19,23 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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) => {
|
||||
export default (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("form", schemas.form, handleZodError),
|
||||
async (context) => {
|
||||
const { client_name, redirect_uris, scopes, website } =
|
||||
extraData.parsedRequest;
|
||||
context.req.valid("form");
|
||||
|
||||
const app = (
|
||||
await db
|
||||
|
|
|
|||
|
|
@ -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,11 +15,13 @@ 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);
|
||||
|
|
@ -34,4 +37,5 @@ export default apiRoute(async (req, matchedRoute, extraData) => {
|
|||
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,21 +20,29 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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 { user } = context.req.valid("header");
|
||||
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { max_id, since_id, min_id, limit } = extraData.parsedRequest;
|
||||
|
||||
const { objects: blocks, link } = await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
|
|
@ -41,7 +51,7 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${user.id} AND "Relationships"."blocking" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
|
|
|
|||
|
|
@ -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,7 +16,8 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async () => {
|
||||
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: {
|
||||
|
|
|
|||
|
|
@ -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,22 +19,31 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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);
|
||||
|
||||
const { objects, link } = await Timeline.getNoteTimeline(
|
||||
const { objects: favourites, link } =
|
||||
await Timeline.getNoteTimeline(
|
||||
and(
|
||||
max_id ? lt(Notes.id, max_id) : undefined,
|
||||
since_id ? gte(Notes.id, since_id) : undefined,
|
||||
|
|
@ -40,11 +51,13 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
sql`EXISTS (SELECT 1 FROM "Likes" WHERE "Likes"."likedId" = ${Notes.id} AND "Likes"."likerId" = ${user.id})`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(objects.map(async (note) => note.toAPI(user))),
|
||||
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,22 +19,31 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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(20),
|
||||
});
|
||||
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);
|
||||
|
||||
const { objects, link } = await Timeline.getUserTimeline(
|
||||
const { objects: followRequests, link } =
|
||||
await Timeline.getUserTimeline(
|
||||
and(
|
||||
max_id ? lt(Users.id, max_id) : undefined,
|
||||
since_id ? gte(Users.id, since_id) : undefined,
|
||||
|
|
@ -40,11 +51,11 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${user.id} AND "Relationships"."ownerId" = ${Users.id} AND "Relationships"."requested" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
context.req.url,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
objects.map((user) => user.toAPI()),
|
||||
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,9 +18,8 @@ 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.",
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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,55 +22,22 @@ 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;
|
||||
|
||||
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 statusCount = await Note.getCount();
|
||||
|
||||
const userCount = (
|
||||
await db
|
||||
.select({
|
||||
count: count(),
|
||||
})
|
||||
.from(Users)
|
||||
.where(isNull(Users.instanceId))
|
||||
)[0].count;
|
||||
const userCount = await User.getCount();
|
||||
|
||||
const contactAccount = await User.fromSql(
|
||||
and(isNull(Users.instanceId), eq(Users.isAdmin, true)),
|
||||
);
|
||||
|
||||
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 monthlyActiveUsers = await User.getActiveInPeriod(
|
||||
30 * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
|
||||
const knownDomainsCount = (
|
||||
await db
|
||||
|
|
@ -86,15 +56,16 @@ export default apiRoute(async (req, matchedRoute, extraData) => {
|
|||
config.validation.max_poll_option_size,
|
||||
max_expiration: config.validation.max_poll_duration,
|
||||
max_options: config.validation.max_poll_options,
|
||||
min_expiration: 60,
|
||||
min_expiration: config.validation.min_poll_duration,
|
||||
},
|
||||
statuses: {
|
||||
characters_reserved_per_url: 0,
|
||||
max_characters: config.validation.max_note_size,
|
||||
max_media_attachments: config.validation.max_media_attachments,
|
||||
max_media_attachments:
|
||||
config.validation.max_media_attachments,
|
||||
},
|
||||
},
|
||||
description: "A test instance",
|
||||
description: config.instance.description,
|
||||
email: "",
|
||||
invites_enabled: false,
|
||||
registrations: config.signups.registration,
|
||||
|
|
|
|||
|
|
@ -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,9 +15,12 @@ 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 (context) => {
|
||||
return jsonResponse(
|
||||
config.signups.rules.map((rule, index) => ({
|
||||
id: String(index),
|
||||
|
|
@ -23,4 +28,5 @@ export default apiRoute(async (req, matchedRoute, extraData) => {
|
|||
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), {
|
||||
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}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
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,25 +29,33 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
timeline: z
|
||||
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) {
|
||||
switch (context.req.method) {
|
||||
case "GET": {
|
||||
const { timeline } = extraData.parsedRequest;
|
||||
|
||||
if (!timeline) {
|
||||
return jsonResponse({});
|
||||
}
|
||||
|
|
@ -72,7 +90,9 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
markers.home = {
|
||||
last_read_id: found.noteId,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(found.createdAt).toISOString(),
|
||||
updated_at: new Date(
|
||||
found.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -102,18 +122,21 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
markers.notifications = {
|
||||
last_read_id: found.notificationId,
|
||||
version: totalCount[0].count,
|
||||
updated_at: new Date(found.createdAt).toISOString(),
|
||||
updated_at: new Date(
|
||||
found.createdAt,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return jsonResponse(markers);
|
||||
}
|
||||
|
||||
case "POST": {
|
||||
const {
|
||||
"home[last_read_id]": home_id,
|
||||
"notifications[last_read_id]": notifications_id,
|
||||
} = extraData.parsedRequest;
|
||||
} = context.req.valid("query");
|
||||
|
||||
const markers: APIMarker = {
|
||||
home: undefined,
|
||||
|
|
|
|||
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,7 +26,8 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
export const schemas = {
|
||||
form: z.object({
|
||||
file: z.instanceof(File),
|
||||
thumbnail: z.instanceof(File).optional(),
|
||||
description: z
|
||||
|
|
@ -32,22 +35,18 @@ export const schema = z.object({
|
|||
.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;
|
||||
|
||||
if (!user) {
|
||||
return errorResponse("Unauthorized", 401);
|
||||
}
|
||||
|
||||
const { file, thumbnail, description } = extraData.parsedRequest;
|
||||
|
||||
const config = await extraData.configManager.getConfig();
|
||||
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 (file.size > config.validation.max_media_size) {
|
||||
return errorResponse(
|
||||
|
|
|
|||
|
|
@ -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,17 +20,25 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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);
|
||||
|
||||
|
|
@ -40,9 +50,15 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
sql`EXISTS (SELECT 1 FROM "Relationships" WHERE "Relationships"."subjectId" = ${Users.id} AND "Relationships"."ownerId" = ${user.id} AND "Relationships"."muting" = true)`,
|
||||
),
|
||||
limit,
|
||||
req.url,
|
||||
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),
|
||||
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), {
|
||||
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),
|
||||
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),
|
||||
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(
|
||||
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,8 +18,13 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export default apiRoute(async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
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
|
||||
|
|
@ -29,4 +35,5 @@ export default apiRoute(async (req, matchedRoute, extraData) => {
|
|||
.where(eq(Notifications.notifiedId, user.id));
|
||||
|
||||
return jsonResponse({});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -17,18 +17,26 @@ let notifications: APINotification[] = [];
|
|||
|
||||
// Create some test notifications
|
||||
beforeAll(async () => {
|
||||
await fetch(
|
||||
new URL(`/api/v1/accounts/${users[0].id}/follow`, config.http.base_url),
|
||||
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({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
for (const i of [0, 1, 2, 3]) {
|
||||
await fetch(
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${statuses[i].id}/favourite`,
|
||||
config.http.base_url,
|
||||
|
|
@ -37,18 +45,20 @@ beforeAll(async () => {
|
|||
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), {
|
||||
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,23 +20,36 @@ 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 (app: Hono) =>
|
||||
app.on(
|
||||
meta.allowedMethods,
|
||||
meta.route,
|
||||
zValidator("query", schemas.query, handleZodError),
|
||||
auth(meta.auth),
|
||||
async (context) => {
|
||||
const { user } = context.req.valid("header");
|
||||
|
||||
export default apiRoute<typeof meta, typeof schema>(
|
||||
async (req, matchedRoute, extraData) => {
|
||||
const { user } = extraData.auth;
|
||||
if (!user) return errorResponse("Unauthorized", 401);
|
||||
|
||||
const { ids } = extraData.parsedRequest;
|
||||
const { "ids[]": ids } = context.req.valid("query");
|
||||
|
||||
await db
|
||||
.update(Notifications)
|
||||
.set({
|
||||
dismissed: true,
|
||||
})
|
||||
.where(inArray(Notifications.id, ids));
|
||||
.where(
|
||||
and(
|
||||
inArray(Notifications.id, ids),
|
||||
eq(Notifications.notifiedId, user.id),
|
||||
),
|
||||
);
|
||||
|
||||
return jsonResponse({});
|
||||
},
|
||||
|
|
|
|||
|
|
@ -11,21 +11,37 @@ 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),
|
||||
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(
|
||||
expect(res1.status).toBe(200);
|
||||
|
||||
const res2 = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${timeline[0].id}/favourite`,
|
||||
config.http.base_url,
|
||||
|
|
@ -34,11 +50,17 @@ beforeAll(async () => {
|
|||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
await fetch(
|
||||
expect(res2.status).toBe(200);
|
||||
|
||||
const res3 = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${timeline[0].id}/reblog`,
|
||||
config.http.base_url,
|
||||
|
|
@ -48,21 +70,28 @@ beforeAll(async () => {
|
|||
headers: {
|
||||
Authorization: `Bearer ${tokens[1].accessToken}`,
|
||||
},
|
||||
body: getFormData({}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
await fetch(new URL("/api/v1/statuses", config.http.base_url), {
|
||||
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}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
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,11 +24,12 @@ export const meta = applyConfig({
|
|||
},
|
||||
});
|
||||
|
||||
export const schema = z.object({
|
||||
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).optional().default(15),
|
||||
limit: z.coerce.number().int().min(1).max(80).default(15),
|
||||
exclude_types: z
|
||||
.enum([
|
||||
"mention",
|
||||
|
|
@ -78,12 +81,17 @@ export const schema = z.object({
|
|||
.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);
|
||||
|
||||
const {
|
||||
|
|
@ -94,10 +102,13 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
min_id,
|
||||
since_id,
|
||||
types,
|
||||
} = extraData.parsedRequest;
|
||||
} = context.req.valid("query");
|
||||
|
||||
if (types && exclude_types) {
|
||||
return errorResponse("Can't use both types and exclude_types", 400);
|
||||
return errorResponse(
|
||||
"Can't use both types and exclude_types",
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
const { objects, link } =
|
||||
|
|
@ -111,11 +122,15 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
{ lt, gte, gt, and, eq, not, inArray },
|
||||
) =>
|
||||
and(
|
||||
max_id ? lt(notification.id, max_id) : undefined,
|
||||
max_id
|
||||
? lt(notification.id, max_id)
|
||||
: undefined,
|
||||
since_id
|
||||
? gte(notification.id, since_id)
|
||||
: undefined,
|
||||
min_id ? gt(notification.id, min_id) : undefined,
|
||||
min_id
|
||||
? gt(notification.id, min_id)
|
||||
: undefined,
|
||||
eq(notification.notifiedId, user.id),
|
||||
eq(notification.dismissed, false),
|
||||
account_id
|
||||
|
|
@ -126,7 +141,12 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
? inArray(notification.type, types)
|
||||
: undefined,
|
||||
exclude_types
|
||||
? not(inArray(notification.type, 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)
|
||||
|
|
@ -141,7 +161,8 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
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 "Notes"."content" LIKE
|
||||
'%' || "FilterKeywords"."keyword" || '%'
|
||||
AND "n_inner"."id" = "Notifications"."id"
|
||||
)
|
||||
AND "Filters"."context" @> ARRAY['notifications']
|
||||
|
|
@ -149,9 +170,10 @@ export default apiRoute<typeof meta, typeof schema>(
|
|||
),
|
||||
limit,
|
||||
// @ts-expect-error Yes I KNOW the types are wrong
|
||||
orderBy: (notification, { desc }) => desc(notification.id),
|
||||
orderBy: (notification, { desc }) =>
|
||||
desc(notification.id),
|
||||
},
|
||||
req,
|
||||
context.req.raw,
|
||||
);
|
||||
|
||||
return jsonResponse(
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
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: "",
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
// 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: "",
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
|
|
|||
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,7 +20,8 @@ afterAll(async () => {
|
|||
|
||||
beforeAll(async () => {
|
||||
for (const status of timeline) {
|
||||
const res = await fetch(
|
||||
const res = await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/favourite`,
|
||||
config.http.base_url,
|
||||
|
|
@ -31,6 +32,7 @@ beforeAll(async () => {
|
|||
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,7 +20,8 @@ afterAll(async () => {
|
|||
|
||||
beforeAll(async () => {
|
||||
for (const status of timeline) {
|
||||
await fetch(
|
||||
await sendTestRequest(
|
||||
new Request(
|
||||
new URL(
|
||||
`/api/v1/statuses/${status.id}/reblog`,
|
||||
config.http.base_url,
|
||||
|
|
@ -31,6 +32,7 @@ beforeAll(async () => {
|
|||
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