2023-10-05 09:00:51 +00:00
|
|
|
import { deepMerge } from "std/collections/deep_merge.ts";
|
|
|
|
import { getLogger } from "std/log/mod.ts";
|
2023-10-08 21:23:54 +00:00
|
|
|
import { createEndpoint, createMethodFilter } from "t_rest/server";
|
2023-10-05 09:00:51 +00:00
|
|
|
import { configSchema, getConfig, setConfig } from "../app/config.ts";
|
|
|
|
import { bot } from "../bot/mod.ts";
|
|
|
|
import { sessions } from "./sessionsRoute.ts";
|
|
|
|
|
|
|
|
export const logger = () => getLogger();
|
|
|
|
|
2023-10-08 21:23:54 +00:00
|
|
|
export const paramsRoute = createMethodFilter({
|
|
|
|
GET: createEndpoint(
|
2023-10-05 09:00:51 +00:00
|
|
|
{ query: null, body: null },
|
|
|
|
async () => {
|
|
|
|
const config = await getConfig();
|
2023-10-08 21:23:54 +00:00
|
|
|
return { status: 200, body: { type: "application/json", data: config.defaultParams } };
|
2023-10-05 09:00:51 +00:00
|
|
|
},
|
|
|
|
),
|
|
|
|
|
2023-10-08 21:23:54 +00:00
|
|
|
PATCH: createEndpoint(
|
2023-10-05 09:00:51 +00:00
|
|
|
{
|
|
|
|
query: { sessionId: { type: "string" } },
|
|
|
|
body: {
|
|
|
|
type: "application/json",
|
|
|
|
schema: configSchema.properties.defaultParams,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
async ({ query, body }) => {
|
|
|
|
const session = sessions.get(query.sessionId);
|
|
|
|
if (!session?.userId) {
|
2023-10-08 21:23:54 +00:00
|
|
|
return { status: 401, body: { type: "text/plain", data: "Must be logged in" } };
|
2023-10-05 09:00:51 +00:00
|
|
|
}
|
|
|
|
const chat = await bot.api.getChat(session.userId);
|
|
|
|
if (chat.type !== "private") {
|
|
|
|
throw new Error("Chat is not private");
|
|
|
|
}
|
|
|
|
const userName = chat.username;
|
|
|
|
if (!userName) {
|
2023-10-08 21:23:54 +00:00
|
|
|
return { status: 403, body: { type: "text/plain", data: "Must have a username" } };
|
2023-10-05 09:00:51 +00:00
|
|
|
}
|
|
|
|
const config = await getConfig();
|
|
|
|
if (!config?.adminUsernames?.includes(userName)) {
|
2023-10-08 21:23:54 +00:00
|
|
|
return { status: 403, body: { type: "text/plain", data: "Must be an admin" } };
|
2023-10-05 09:00:51 +00:00
|
|
|
}
|
2023-10-08 21:23:54 +00:00
|
|
|
logger().info(`User ${userName} updated default params: ${JSON.stringify(body.data)}`);
|
|
|
|
const defaultParams = deepMerge(config.defaultParams ?? {}, body.data);
|
2023-10-05 09:00:51 +00:00
|
|
|
await setConfig({ defaultParams });
|
2023-10-08 21:23:54 +00:00
|
|
|
return { status: 200, body: { type: "application/json", data: config.defaultParams } };
|
2023-10-05 09:00:51 +00:00
|
|
|
},
|
|
|
|
),
|
2023-10-08 21:23:54 +00:00
|
|
|
});
|