refactor: rewrite API to Elysia #25

Merged
pinks merged 2 commits from elysia into main 2023-11-20 02:14:15 +00:00
33 changed files with 961 additions and 897 deletions

View File

@ -1,129 +1,128 @@
import { Model } from "indexed_kv";
import { info } from "std/log/mod.ts"; import { info } from "std/log/mod.ts";
import { createEndpoint, createMethodFilter, createPathFilter } from "t_rest/server"; import { Elysia, Static, t } from "elysia";
import { Admin, adminSchema, adminStore } from "../app/adminStore.ts"; import { Admin, adminSchema, adminStore } from "../app/adminStore.ts";
import { getUser, withAdmin, withUser } from "./withUser.ts"; import { getUser, withSessionAdmin, withSessionUser } from "./getUser.ts";
import { TkvEntry } from "../utils/Tkv.ts";
export type AdminData = Admin & { id: string }; const adminDataSchema = t.Intersect([adminSchema, t.Object({ tgUserId: t.Number() })]);
function getAdminData(adminEntry: Model<Admin>): AdminData { export type AdminData = Static<typeof adminDataSchema>;
return { id: adminEntry.id, ...adminEntry.value };
function getAdminData(adminEntry: TkvEntry<["admins", number], Admin>): AdminData {
return { tgUserId: adminEntry.key[1], ...adminEntry.value };
} }
export const adminsRoute = createPathFilter({ export const adminsRoute = new Elysia()
"": createMethodFilter({ .get(
GET: createEndpoint( "",
{},
async () => { async () => {
const adminEntries = await adminStore.getAll(); const adminEntries = await Array.fromAsync(adminStore.list({ prefix: ["admins"] }));
const admins = adminEntries.map(getAdminData); const admins = adminEntries.map(getAdminData);
return { return admins;
status: 200,
body: { type: "application/json", data: admins satisfies AdminData[] },
};
}, },
),
POST: createEndpoint(
{ {
query: { response: t.Array(adminDataSchema),
sessionId: { type: "string" },
}, },
body: { )
type: "application/json", .post(
schema: { "",
type: "object", async ({ query, body, set }) => {
properties: { return withSessionAdmin({ query, set }, async (sessionUser, sessionAdminEntry) => {
tgUserId: adminSchema.properties.tgUserId, const newAdminUser = await getUser(body.tgUserId);
}, const newAdminKey = ["admins", body.tgUserId] as const;
required: ["tgUserId"], const newAdminValue = { promotedBy: sessionAdminEntry.key[1] };
}, const newAdminResult = await adminStore.atomicSet(newAdminKey, null, newAdminValue);
}, if (!newAdminResult.ok) {
}, set.status = 409;
async ({ query, body }) => { return "User is already an admin";
return withAdmin(query, async (user, adminEntry) => { }
const newAdminUser = await getUser(body.data.tgUserId); info(`User ${sessionUser.first_name} promoted user ${newAdminUser.first_name} to admin`);
const newAdminEntry = await adminStore.create({ return getAdminData({ ...newAdminResult, key: newAdminKey, value: newAdminValue });
tgUserId: body.data.tgUserId,
promotedBy: adminEntry.id,
});
info(`User ${user.first_name} promoted user ${newAdminUser.first_name} to admin`);
return {
status: 200,
body: { type: "application/json", data: getAdminData(newAdminEntry) },
};
}); });
}, },
), {
query: t.Object({ sessionId: t.String() }),
body: t.Object({
tgUserId: t.Number(),
}), }),
response: {
"promote_self": createMethodFilter({ 200: adminDataSchema,
POST: createEndpoint( 401: t.Literal("Must be logged in"),
{ 403: t.Literal("Must be an admin"),
query: { 409: t.Literal("User is already an admin"),
sessionId: { type: "string" },
}, },
}, },
)
.post(
"/promote_self",
// if there are no admins, allow any user to promote themselves // if there are no admins, allow any user to promote themselves
async ({ query }) => { async ({ query, set }) => {
return withUser(query, async (user) => { return withSessionUser({ query, set }, async (sessionUser) => {
const adminEntries = await adminStore.getAll(); const adminEntries = await Array.fromAsync(adminStore.list({ prefix: ["admins"] }));
if (adminEntries.length === 0) { if (adminEntries.length !== 0) {
const newAdminEntry = await adminStore.create({ set.status = 409;
tgUserId: user.id, return "You are not allowed to promote yourself";
promotedBy: null,
});
info(`User ${user.first_name} promoted themselves to admin`);
return {
status: 200,
body: { type: "application/json", data: getAdminData(newAdminEntry) },
};
} }
return { const newAdminKey = ["admins", sessionUser.id] as const;
status: 403, const newAdminValue = { promotedBy: null };
body: { type: "text/plain", data: `You are not allowed to promote yourself` }, const newAdminResult = await adminStore.set(newAdminKey, newAdminValue);
}; info(`User ${sessionUser.first_name} promoted themselves to admin`);
return getAdminData({ ...newAdminResult, key: newAdminKey, value: newAdminValue });
}); });
}, },
),
}),
"{adminId}": createPathFilter({
"": createMethodFilter({
GET: createEndpoint(
{},
async ({ params }) => {
const adminEntry = await adminStore.getById(params.adminId!);
if (!adminEntry) {
return { status: 404, body: { type: "text/plain", data: `Admin not found` } };
}
return {
status: 200,
body: { type: "application/json", data: getAdminData(adminEntry) },
};
},
),
DELETE: createEndpoint(
{ {
query: { query: t.Object({ sessionId: t.String() }),
sessionId: { type: "string" }, response: {
200: adminDataSchema,
401: t.Literal("Must be logged in"),
403: t.Literal("Must be an admin"),
409: t.Literal("You are not allowed to promote yourself"),
}, },
}, },
async ({ params, query }) => { )
return withAdmin(query, async (chat) => { .get(
const deletedAdminEntry = await adminStore.getById(params.adminId!); "/:adminId",
if (!deletedAdminEntry) { async ({ params, set }) => {
return { status: 404, body: { type: "text/plain", data: `Admin not found` } }; const adminEntry = await adminStore.get(["admins", Number(params.adminId)]);
if (!adminEntry.versionstamp) {
set.status = 404;
return "Admin not found";
} }
const deletedAdminUser = await getUser(deletedAdminEntry.value.tgUserId); return getAdminData(adminEntry);
await deletedAdminEntry.delete(); },
info(`User ${chat.first_name} demoted user ${deletedAdminUser.first_name} from admin`); {
return { params: t.Object({ adminId: t.String() }),
status: 200, response: {
body: { type: "application/json", data: null }, 200: adminDataSchema,
}; 404: t.Literal("Admin not found"),
},
},
)
.delete(
"/:adminId",
async ({ params, query, set }) => {
return withSessionAdmin({ query, set }, async (sessionUser) => {
const deletedAdminEntry = await adminStore.get(["admins", Number(params.adminId)]);
if (!deletedAdminEntry.versionstamp) {
set.status = 404;
return "Admin not found";
}
const deletedAdminUser = await getUser(deletedAdminEntry.key[1]);
await adminStore.delete(["admins", Number(params.adminId)]);
info(
`User ${sessionUser.first_name} demoted user ${deletedAdminUser.first_name} from admin`,
);
return null;
}); });
}, },
), {
}), params: t.Object({ adminId: t.String() }),
}), query: t.Object({ sessionId: t.String() }),
}); response: {
200: t.Null(),
401: t.Literal("Must be logged in"),
403: t.Literal("Must be an admin"),
404: t.Literal("Admin not found"),
},
},
);

View File

@ -1,9 +1,14 @@
import { createEndpoint, createMethodFilter } from "t_rest/server"; import { Elysia, t } from "elysia";
import { bot } from "../bot/mod.ts"; import { bot } from "../bot/mod.ts";
export const botRoute = createMethodFilter({ export const botRoute = new Elysia()
GET: createEndpoint({ query: null, body: null }, async () => { .get(
"",
async () => {
const username = bot.botInfo.username; const username = bot.botInfo.username;
return { status: 200, body: { type: "application/json", data: { username } } }; return { username };
}), },
}); {
response: t.Object({ username: t.String() }),
},
);

45
api/getUser.ts Normal file
View File

@ -0,0 +1,45 @@
import { Chat } from "grammy_types";
import { Admin, adminStore } from "../app/adminStore.ts";
import { bot } from "../bot/mod.ts";
import { sessions } from "./sessionsRoute.ts";
import { TkvEntry } from "../utils/Tkv.ts";
export async function withSessionUser<O>(
{ query, set }: { query: { sessionId: string }; set: { status?: string | number } },
cb: (sessionUser: Chat.PrivateGetChat) => Promise<O>,
) {
const session = sessions.get(query.sessionId);
if (!session?.userId) {
set.status = 401;
return "Must be logged in";
}
const user = await getUser(session.userId);
return cb(user);
}
export async function withSessionAdmin<O>(
{ query, set }: { query: { sessionId: string }; set: { status?: string | number } },
cb: (
sessionUser: Chat.PrivateGetChat,
sessionAdminEntry: TkvEntry<["admins", number], Admin>,
) => Promise<O>,
) {
const session = sessions.get(query.sessionId);
if (!session?.userId) {
set.status = 401;
return "Must be logged in";
}
const sessionUser = await getUser(session.userId);
const sessionAdminEntry = await adminStore.get(["admins", sessionUser.id]);
if (!sessionAdminEntry.versionstamp) {
set.status = 403;
return "Must be an admin";
}
return cb(sessionUser, sessionAdminEntry);
}
export async function getUser(userId: number): Promise<Chat.PrivateGetChat> {
const chat = await bot.api.getChat(userId);
if (chat.type !== "private") throw new Error("Chat is not private");
return chat;
}

View File

@ -1,32 +1,40 @@
import { createEndpoint, createMethodFilter } from "t_rest/server"; import { Elysia, t } from "elysia";
import { generationQueue } from "../app/generationQueue.ts"; import { generationQueue } from "../app/generationQueue.ts";
export const jobsRoute = createMethodFilter({ export const jobsRoute = new Elysia()
GET: createEndpoint( .get(
{ query: null, body: null }, "",
async () => { async () => {
const allJobs = await generationQueue.getAllJobs(); const allJobs = await generationQueue.getAllJobs();
const filteredJobsData = allJobs.map((job) => ({ return allJobs.map((job) => ({
id: job.id, id: job.id.join(":"),
place: job.place, place: job.place,
state: { state: {
from: { from: {
language_code: job.state.from.language_code, language_code: job.state.from.language_code ?? null,
first_name: job.state.from.first_name, first_name: job.state.from.first_name,
last_name: job.state.from.last_name, last_name: job.state.from.last_name ?? null,
username: job.state.from.username, username: job.state.from.username ?? null,
}, },
progress: job.state.progress, progress: job.state.progress ?? null,
workerInstanceKey: job.state.workerInstanceKey, workerInstanceKey: job.state.workerInstanceKey ?? null,
}, },
})); }));
return {
status: 200,
body: {
type: "application/json",
data: filteredJobsData,
}, },
}; {
response: t.Array(t.Object({
id: t.String(),
place: t.Number(),
state: t.Object({
from: t.Object({
language_code: t.Nullable(t.String()),
first_name: t.String(),
last_name: t.Nullable(t.String()),
username: t.Nullable(t.String()),
}),
progress: t.Nullable(t.Number()),
workerInstanceKey: t.Nullable(t.String()),
}),
})),
}, },
), );
});

View File

@ -1,12 +1,12 @@
import { route } from "reroute"; import { route } from "reroute";
import { serveSpa } from "serve_spa"; import { serveSpa } from "serve_spa";
import { serveApi } from "./serveApi.ts"; import { api } from "./serveApi.ts";
import { fromFileUrl } from "std/path/mod.ts"; import { fromFileUrl } from "std/path/mod.ts";
export async function serveUi() { export async function serveUi() {
const server = Deno.serve({ port: 5999 }, (request) => const server = Deno.serve({ port: 5999 }, (request) =>
route(request, { route(request, {
"/api/*": (request) => serveApi(request), "/api/*": (request) => api.fetch(request),
"/*": (request) => "/*": (request) =>
serveSpa(request, { serveSpa(request, {
fsRoot: fromFileUrl(new URL("../ui/", import.meta.url)), fsRoot: fromFileUrl(new URL("../ui/", import.meta.url)),

View File

@ -1,34 +1,39 @@
import { deepMerge } from "std/collections/deep_merge.ts"; import { Elysia, t } from "elysia";
import { info } from "std/log/mod.ts"; import { info } from "std/log/mod.ts";
import { createEndpoint, createMethodFilter } from "t_rest/server"; import { defaultParamsSchema, getConfig, setConfig } from "../app/config.ts";
import { configSchema, getConfig, setConfig } from "../app/config.ts"; import { withSessionAdmin } from "./getUser.ts";
import { withAdmin } from "./withUser.ts";
export const paramsRoute = createMethodFilter({ export const paramsRoute = new Elysia()
GET: createEndpoint( .get(
{ query: null, body: null }, "",
async () => { async () => {
const config = await getConfig(); const config = await getConfig();
return { status: 200, body: { type: "application/json", data: config.defaultParams } }; return config.defaultParams;
}, },
),
PATCH: createEndpoint(
{ {
query: { sessionId: { type: "string" } }, response: {
body: { 200: defaultParamsSchema,
type: "application/json",
schema: configSchema.properties.defaultParams,
}, },
}, },
async ({ query, body }) => { )
return withAdmin(query, async (user) => { .patch(
"",
async ({ query, body, set }) => {
return withSessionAdmin({ query, set }, async (user) => {
const config = await getConfig(); const config = await getConfig();
info(`User ${user.first_name} updated default params: ${JSON.stringify(body.data)}`); info(`User ${user.first_name} updated default params: ${JSON.stringify(body)}`);
const defaultParams = deepMerge(config.defaultParams ?? {}, body.data); const defaultParams = { ...config.defaultParams, ...body };
await setConfig({ defaultParams }); await setConfig({ defaultParams });
return { status: 200, body: { type: "application/json", data: config.defaultParams } }; return config.defaultParams;
}); });
}, },
), {
}); query: t.Object({ sessionId: t.String() }),
body: defaultParamsSchema,
response: {
200: defaultParamsSchema,
401: t.Literal("Must be logged in"),
403: t.Literal("Must be an admin"),
},
},
);

View File

@ -1,4 +1,5 @@
import { createLoggerMiddleware, createPathFilter } from "t_rest/server"; import { Elysia } from "elysia";
import { swagger } from "elysia/swagger";
import { adminsRoute } from "./adminsRoute.ts"; import { adminsRoute } from "./adminsRoute.ts";
import { botRoute } from "./botRoute.ts"; import { botRoute } from "./botRoute.ts";
import { jobsRoute } from "./jobsRoute.ts"; import { jobsRoute } from "./jobsRoute.ts";
@ -8,18 +9,24 @@ import { statsRoute } from "./statsRoute.ts";
import { usersRoute } from "./usersRoute.ts"; import { usersRoute } from "./usersRoute.ts";
import { workersRoute } from "./workersRoute.ts"; import { workersRoute } from "./workersRoute.ts";
export const serveApi = createLoggerMiddleware( export const api = new Elysia()
createPathFilter({ .use(
"admins": adminsRoute, swagger({
"bot": botRoute, path: "/docs",
"jobs": jobsRoute, swaggerOptions: { url: "docs/json" } as never,
"sessions": sessionsRoute, documentation: {
"settings/params": paramsRoute, info: { title: "Eris API", version: "0.1" },
"stats": statsRoute, servers: [{ url: "/api" }],
"users": usersRoute, },
"workers": workersRoute,
}), }),
{ filterStatus: (status) => status >= 400 }, )
); .group("/admins", (api) => api.use(adminsRoute))
.group("/bot", (api) => api.use(botRoute))
.group("/jobs", (api) => api.use(jobsRoute))
.group("/sessions", (api) => api.use(sessionsRoute))
.group("/settings/params", (api) => api.use(paramsRoute))
.group("/stats", (api) => api.use(statsRoute))
.group("/users", (api) => api.use(usersRoute))
.group("/workers", (api) => api.use(workersRoute));
export type ApiHandler = typeof serveApi; export type Api = typeof api;

View File

@ -1,4 +1,4 @@
import { createEndpoint, createMethodFilter, createPathFilter } from "t_rest/server"; import { Elysia, NotFoundError, t } from "elysia";
import { ulid } from "ulid"; import { ulid } from "ulid";
export const sessions = new Map<string, Session>(); export const sessions = new Map<string, Session>();
@ -7,30 +7,37 @@ export interface Session {
userId?: number | undefined; userId?: number | undefined;
} }
export const sessionsRoute = createPathFilter({ export const sessionsRoute = new Elysia()
"": createMethodFilter({ .post(
POST: createEndpoint( "",
{ query: null, body: null },
async () => { async () => {
const id = ulid(); const id = ulid();
const session: Session = {}; const session: Session = {};
sessions.set(id, session); sessions.set(id, session);
return { status: 200, body: { type: "application/json", data: { id, ...session } } }; return { id, userId: session.userId ?? null };
}, },
), {
response: t.Object({
id: t.String(),
userId: t.Nullable(t.Number()),
}), }),
},
"{sessionId}": createMethodFilter({ )
GET: createEndpoint( .get(
{ query: null, body: null }, "/:sessionId",
async ({ params }) => { async ({ params }) => {
const id = params.sessionId!; const id = params.sessionId!;
const session = sessions.get(id); const session = sessions.get(id);
if (!session) { if (!session) {
return { status: 401, body: { type: "text/plain", data: "Session not found" } }; throw new NotFoundError("Session not found");
} }
return { status: 200, body: { type: "application/json", data: { id, ...session } } }; return { id, userId: session.userId ?? null };
}, },
), {
params: t.Object({ sessionId: t.String() }),
response: t.Object({
id: t.String(),
userId: t.Nullable(t.Number()),
}), }),
}); },
);

View File

@ -1,18 +1,17 @@
import { Elysia, t } from "elysia";
import { subMinutes } from "date-fns"; import { subMinutes } from "date-fns";
import { createEndpoint, createMethodFilter, createPathFilter } from "t_rest/server"; import { dailyStatsSchema, getDailyStats } from "../app/dailyStatsStore.ts";
import { getDailyStats } from "../app/dailyStatsStore.ts";
import { generationStore } from "../app/generationStore.ts"; import { generationStore } from "../app/generationStore.ts";
import { globalStats } from "../app/globalStats.ts"; import { globalStats } from "../app/globalStats.ts";
import { getUserDailyStats } from "../app/userDailyStatsStore.ts"; import { getUserDailyStats, userDailyStatsSchema } from "../app/userDailyStatsStore.ts";
import { getUserStats } from "../app/userStatsStore.ts"; import { getUserStats, userStatsSchema } from "../app/userStatsStore.ts";
import { withAdmin } from "./withUser.ts"; import { withSessionAdmin } from "./getUser.ts";
const STATS_INTERVAL_MIN = 3; const STATS_INTERVAL_MIN = 3;
export const statsRoute = createPathFilter({ export const statsRoute = new Elysia()
"": createMethodFilter({ .get(
GET: createEndpoint( "",
{ query: null, body: null },
async () => { async () => {
const after = subMinutes(new Date(), STATS_INTERVAL_MIN); const after = subMinutes(new Date(), STATS_INTERVAL_MIN);
const generations = await generationStore.getAll({ after }); const generations = await generationStore.getAll({ after });
@ -37,10 +36,6 @@ export const statsRoute = createPathFilter({
.reduce((sum, pixelSteps) => sum + pixelSteps, 0) / STATS_INTERVAL_MIN; .reduce((sum, pixelSteps) => sum + pixelSteps, 0) / STATS_INTERVAL_MIN;
return { return {
status: 200,
body: {
type: "application/json",
data: {
imageCount: globalStats.imageCount, imageCount: globalStats.imageCount,
stepCount: globalStats.stepCount, stepCount: globalStats.stepCount,
pixelCount: globalStats.pixelCount, pixelCount: globalStats.pixelCount,
@ -50,97 +45,90 @@ export const statsRoute = createPathFilter({
stepsPerMinute, stepsPerMinute,
pixelsPerMinute, pixelsPerMinute,
pixelStepsPerMinute, pixelStepsPerMinute,
},
},
}; };
}, },
), {
response: {
200: t.Object({
imageCount: t.Number(),
stepCount: t.Number(),
pixelCount: t.Number(),
pixelStepCount: t.Number(),
userCount: t.Number(),
imagesPerMinute: t.Number(),
stepsPerMinute: t.Number(),
pixelsPerMinute: t.Number(),
pixelStepsPerMinute: t.Number(),
}), }),
"daily/{year}/{month}/{day}": createMethodFilter({ },
GET: createEndpoint( },
{ query: null, body: null }, )
.get(
"/daily/:year/:month/:day",
async ({ params }) => { async ({ params }) => {
const year = Number(params.year); return getDailyStats(params.year, params.month, params.day);
const month = Number(params.month);
const day = Number(params.day);
const stats = await getDailyStats(year, month, day);
return {
status: 200,
body: {
type: "application/json",
data: {
imageCount: stats.imageCount,
pixelCount: stats.pixelCount,
userCount: stats.userIds.length,
timestamp: stats.timestamp,
}, },
}, {
}; params: t.Object({
}, year: t.Number(),
), month: t.Number(),
day: t.Number(),
}), }),
"users/{userId}": createMethodFilter({ response: {
GET: createEndpoint( 200: dailyStatsSchema,
{ query: null, body: null }, },
},
)
.get(
"/users/:userId",
async ({ params }) => { async ({ params }) => {
const userId = Number(params.userId); const userId = params.userId;
const stats = await getUserStats(userId); // deno-lint-ignore no-unused-vars
const { tagCountMap, ...stats } = await getUserStats(userId);
return stats;
},
{
params: t.Object({ userId: t.Number() }),
response: {
200: t.Omit(userStatsSchema, ["tagCountMap"]),
},
},
)
.get(
"/users/:userId/tagcount",
async ({ params, query, set }) => {
return withSessionAdmin({ query, set }, async () => {
const stats = await getUserStats(params.userId);
return { return {
status: 200,
body: {
type: "application/json",
data: {
imageCount: stats.imageCount,
pixelCount: stats.pixelCount,
timestamp: stats.timestamp,
},
},
};
},
),
}),
"users/{userId}/tagcount": createMethodFilter({
GET: createEndpoint(
{ query: { sessionId: { type: "string" } }, body: null },
async ({ params, query }) => {
return withAdmin(query, async () => {
const userId = Number(params.userId);
const stats = await getUserStats(userId);
return {
status: 200,
body: {
type: "application/json",
data: {
tagCountMap: stats.tagCountMap, tagCountMap: stats.tagCountMap,
timestamp: stats.timestamp, timestamp: stats.timestamp,
},
},
}; };
}); });
}, },
), {
}), params: t.Object({ userId: t.Number() }),
"users/{userId}/daily/{year}/{month}/{day}": createMethodFilter({ query: t.Object({ sessionId: t.String() }),
GET: createEndpoint( response: {
{ query: null, body: null }, 200: t.Pick(userStatsSchema, ["tagCountMap", "timestamp"]),
401: t.Literal("Must be logged in"),
403: t.Literal("Must be an admin"),
},
},
)
.get(
"/users/:userId/daily/:year/:month/:day",
async ({ params }) => { async ({ params }) => {
const userId = Number(params.userId); return getUserDailyStats(params.userId, params.year, params.month, params.day);
const year = Number(params.year);
const month = Number(params.month);
const day = Number(params.day);
const stats = await getUserDailyStats(userId, year, month, day);
return {
status: 200,
body: {
type: "application/json",
data: {
imageCount: stats.imageCount,
pixelCount: stats.pixelCount,
timestamp: stats.timestamp,
}, },
}, {
}; params: t.Object({
}, userId: t.Number(),
), year: t.Number(),
month: t.Number(),
day: t.Number(),
}), }),
}); response: {
200: userDailyStatsSchema,
},
},
);

View File

@ -1,50 +1,55 @@
import { createEndpoint, createMethodFilter, createPathFilter } from "t_rest/server"; import { Elysia, t } from "elysia";
import { adminSchema, adminStore } from "../app/adminStore.ts";
import { bot } from "../bot/mod.ts"; import { bot } from "../bot/mod.ts";
import { getUser } from "./withUser.ts"; import { getUser } from "./getUser.ts";
import { adminStore } from "../app/adminStore.ts";
export const usersRoute = createPathFilter({ export const usersRoute = new Elysia()
"{userId}/photo": createMethodFilter({ .get(
GET: createEndpoint( "/:userId/photo",
{ query: null, body: null },
async ({ params }) => { async ({ params }) => {
const user = await getUser(Number(params.userId!)); const user = await getUser(Number(params.userId));
const photoData = user.photo?.small_file_id if (!user.photo) {
? await fetch( throw new Error("User has no photo");
`https://api.telegram.org/file/bot${bot.token}/${await bot.api.getFile(
user.photo.small_file_id,
).then((file) => file.file_path)}`,
).then((resp) => resp.arrayBuffer())
: undefined;
if (!photoData) {
return { status: 404, body: { type: "text/plain", data: "User has no photo" } };
} }
return { const photoFile = await bot.api.getFile(user.photo.small_file_id);
status: 200, const photoData = await fetch(
body: { `https://api.telegram.org/file/bot${bot.token}/${photoFile.file_path}`,
type: "image/jpeg", ).then((resp) => {
data: new Blob([photoData], { type: "image/jpeg" }), if (!resp.ok) {
}, throw new Error("Failed to fetch photo");
}; }
}, return resp;
), }).then((resp) => resp.arrayBuffer());
}),
"{userId}": createMethodFilter({ return new Response(new File([photoData], "avatar.jpg", { type: "image/jpeg" }));
GET: createEndpoint(
{ query: null, body: null },
async ({ params }) => {
const user = await getUser(Number(params.userId!));
const [adminEntry] = await adminStore.getBy("tgUserId", { value: user.id });
const admin = adminEntry?.value;
return {
status: 200,
body: {
type: "application/json",
data: { ...user, admin },
}, },
{
params: t.Object({ userId: t.String() }),
},
)
.get(
"/:userId",
async ({ params }) => {
const user = await getUser(Number(params.userId));
const adminEntry = await adminStore.get(["admins", user.id]);
return {
id: user.id,
first_name: user.first_name,
last_name: user.last_name ?? null,
username: user.username ?? null,
bio: user.bio ?? null,
admin: adminEntry.value ?? null,
}; };
}, },
), {
params: t.Object({ userId: t.String() }),
response: t.Object({
id: t.Number(),
first_name: t.String(),
last_name: t.Nullable(t.String()),
username: t.Nullable(t.String()),
bio: t.Nullable(t.String()),
admin: t.Nullable(adminSchema),
}), }),
}); },
);

View File

@ -1,40 +0,0 @@
import { Chat } from "grammy_types";
import { Model } from "indexed_kv";
import { Output } from "t_rest/client";
import { Admin, adminStore } from "../app/adminStore.ts";
import { bot } from "../bot/mod.ts";
import { sessions } from "./sessionsRoute.ts";
export async function withUser<O extends Output>(
query: { sessionId: string },
cb: (user: Chat.PrivateGetChat) => Promise<O>,
) {
const session = sessions.get(query.sessionId);
if (!session?.userId) {
return { status: 401, body: { type: "text/plain", data: "Must be logged in" } } as const;
}
const user = await getUser(session.userId);
return cb(user);
}
export async function withAdmin<O extends Output>(
query: { sessionId: string },
cb: (user: Chat.PrivateGetChat, admin: Model<Admin>) => Promise<O>,
) {
const session = sessions.get(query.sessionId);
if (!session?.userId) {
return { status: 401, body: { type: "text/plain", data: "Must be logged in" } } as const;
}
const user = await getUser(session.userId);
const [admin] = await adminStore.getBy("tgUserId", { value: session.userId });
if (!admin) {
return { status: 403, body: { type: "text/plain", data: "Must be an admin" } } as const;
}
return cb(user, admin);
}
export async function getUser(userId: number): Promise<Chat.PrivateGetChat> {
const chat = await bot.api.getChat(userId);
if (chat.type !== "private") throw new Error("Chat is not private");
return chat;
}

View File

@ -2,7 +2,7 @@ import { subMinutes } from "date-fns";
import { Model } from "indexed_kv"; import { Model } from "indexed_kv";
import createOpenApiFetch from "openapi_fetch"; import createOpenApiFetch from "openapi_fetch";
import { info } from "std/log/mod.ts"; import { info } from "std/log/mod.ts";
import { createEndpoint, createMethodFilter, createPathFilter } from "t_rest/server"; import { Elysia, NotFoundError, Static, t } from "elysia";
import { activeGenerationWorkers } from "../app/generationQueue.ts"; import { activeGenerationWorkers } from "../app/generationQueue.ts";
import { generationStore } from "../app/generationStore.ts"; import { generationStore } from "../app/generationStore.ts";
import * as SdApi from "../app/sdApi.ts"; import * as SdApi from "../app/sdApi.ts";
@ -13,20 +13,27 @@ import {
} from "../app/workerInstanceStore.ts"; } from "../app/workerInstanceStore.ts";
import { getAuthHeader } from "../utils/getAuthHeader.ts"; import { getAuthHeader } from "../utils/getAuthHeader.ts";
import { omitUndef } from "../utils/omitUndef.ts"; import { omitUndef } from "../utils/omitUndef.ts";
import { withAdmin } from "./withUser.ts"; import { withSessionAdmin } from "./getUser.ts";
export type WorkerData = Omit<WorkerInstance, "sdUrl" | "sdAuth"> & { const workerResponseSchema = t.Intersect([
id: string; t.Object({ id: t.String() }),
isActive: boolean; t.Omit(workerInstanceSchema, ["sdUrl", "sdAuth"]),
imagesPerMinute: number; t.Object({
stepsPerMinute: number; isActive: t.Boolean(),
pixelsPerMinute: number; imagesPerMinute: t.Number(),
pixelStepsPerMinute: number; stepsPerMinute: t.Number(),
}; pixelsPerMinute: t.Number(),
pixelStepsPerMinute: t.Number(),
}),
]);
export type WorkerResponse = Static<typeof workerResponseSchema>;
const workerRequestSchema = t.Omit(workerInstanceSchema, ["lastOnlineTime", "lastError"]);
const STATS_INTERVAL_MIN = 10; const STATS_INTERVAL_MIN = 10;
async function getWorkerData(workerInstance: Model<WorkerInstance>): Promise<WorkerData> { async function getWorkerResponse(workerInstance: Model<WorkerInstance>): Promise<WorkerResponse> {
const after = subMinutes(new Date(), STATS_INTERVAL_MIN); const after = subMinutes(new Date(), STATS_INTERVAL_MIN);
const generations = await generationStore.getBy("workerInstanceKey", { const generations = await generationStore.getBy("workerInstanceKey", {
@ -51,7 +58,7 @@ async function getWorkerData(workerInstance: Model<WorkerInstance>): Promise<Wor
) )
.reduce((sum, pixelSteps) => sum + pixelSteps, 0) / STATS_INTERVAL_MIN; .reduce((sum, pixelSteps) => sum + pixelSteps, 0) / STATS_INTERVAL_MIN;
return { return omitUndef({
id: workerInstance.id, id: workerInstance.id,
key: workerInstance.value.key, key: workerInstance.value.key,
name: workerInstance.value.name, name: workerInstance.value.name,
@ -62,117 +69,113 @@ async function getWorkerData(workerInstance: Model<WorkerInstance>): Promise<Wor
stepsPerMinute, stepsPerMinute,
pixelsPerMinute, pixelsPerMinute,
pixelStepsPerMinute, pixelStepsPerMinute,
}; });
} }
export const workersRoute = createPathFilter({ export const workersRoute = new Elysia()
"": createMethodFilter({ .get(
GET: createEndpoint( "",
{ query: null, body: null },
async () => { async () => {
const workerInstances = await workerInstanceStore.getAll(); const workerInstances = await workerInstanceStore.getAll();
const workers = await Promise.all(workerInstances.map(getWorkerData)); const workers = await Promise.all(workerInstances.map(getWorkerResponse));
return { return workers;
status: 200,
body: { type: "application/json", data: workers satisfies WorkerData[] },
};
}, },
),
POST: createEndpoint(
{ {
query: { response: t.Array(workerResponseSchema),
sessionId: { type: "string" },
}, },
body: { )
type: "application/json", .post(
schema: workerInstanceSchema, "",
}, async ({ query, body, set }) => {
}, return withSessionAdmin({ query, set }, async (sessionUser) => {
async ({ query, body }) => { const workerInstance = await workerInstanceStore.create(body);
return withAdmin(query, async (user) => { info(`User ${sessionUser.first_name} created worker ${workerInstance.value.name}`);
const workerInstance = await workerInstanceStore.create(body.data); return await getWorkerResponse(workerInstance);
info(`User ${user.first_name} created worker ${workerInstance.value.name}`);
return {
status: 200,
body: { type: "application/json", data: await getWorkerData(workerInstance) },
};
}); });
}, },
),
}),
"{workerId}": createPathFilter({
"": createMethodFilter({
GET: createEndpoint(
{ query: null, body: null },
async ({ params }) => {
const workerInstance = await workerInstanceStore.getById(params.workerId!);
if (!workerInstance) {
return { status: 404, body: { type: "text/plain", data: `Worker not found` } };
}
return {
status: 200,
body: { type: "application/json", data: await getWorkerData(workerInstance) },
};
},
),
PATCH: createEndpoint(
{ {
query: { query: t.Object({ sessionId: t.String() }),
sessionId: { type: "string" }, body: workerRequestSchema,
}, response: {
body: { 200: workerResponseSchema,
type: "application/json", 401: t.Literal("Must be logged in"),
schema: { ...workerInstanceSchema, required: [] }, 403: t.Literal("Must be an admin"),
}, },
}, },
async ({ params, query, body }) => { )
const workerInstance = await workerInstanceStore.getById(params.workerId!); .get(
"/:workerId",
async ({ params }) => {
const workerInstance = await workerInstanceStore.getById(params.workerId);
if (!workerInstance) { if (!workerInstance) {
return { status: 404, body: { type: "text/plain", data: `Worker not found` } }; throw new NotFoundError("Worker not found");
} }
return withAdmin(query, async (user) => { return await getWorkerResponse(workerInstance);
},
{
params: t.Object({ workerId: t.String() }),
response: {
200: workerResponseSchema,
},
},
)
.patch(
"/:workerId",
async ({ params, query, body, set }) => {
const workerInstance = await workerInstanceStore.getById(params.workerId);
if (!workerInstance) {
throw new NotFoundError("Worker not found");
}
return withSessionAdmin({ query, set }, async (sessionUser) => {
info( info(
`User ${user.first_name} updated worker ${workerInstance.value.name}: ${ `User ${sessionUser.first_name} updated worker ${workerInstance.value.name}: ${
JSON.stringify(body.data) JSON.stringify(body)
}`, }`,
); );
await workerInstance.update(omitUndef(body.data)); await workerInstance.update(body);
return { return await getWorkerResponse(workerInstance);
status: 200,
body: { type: "application/json", data: await getWorkerData(workerInstance) },
};
}); });
}, },
),
DELETE: createEndpoint(
{ {
query: { params: t.Object({ workerId: t.String() }),
sessionId: { type: "string" }, query: t.Object({ sessionId: t.String() }),
body: t.Partial(workerRequestSchema),
response: {
200: workerResponseSchema,
401: t.Literal("Must be logged in"),
403: t.Literal("Must be an admin"),
}, },
body: null,
}, },
async ({ params, query }) => { )
const workerInstance = await workerInstanceStore.getById(params.workerId!); .delete(
"/:workerId",
async ({ params, query, set }) => {
const workerInstance = await workerInstanceStore.getById(params.workerId);
if (!workerInstance) { if (!workerInstance) {
return { status: 404, body: { type: "text/plain", data: `Worker not found` } }; throw new Error("Worker not found");
} }
return withAdmin(query, async (user) => { return withSessionAdmin({ query, set }, async (sessionUser) => {
info(`User ${user.first_name} deleted worker ${workerInstance.value.name}`); info(`User ${sessionUser.first_name} deleted worker ${workerInstance.value.name}`);
await workerInstance.delete(); await workerInstance.delete();
return { status: 200, body: { type: "application/json", data: null } }; return null;
}); });
}, },
), {
}), params: t.Object({ workerId: t.String() }),
query: t.Object({ sessionId: t.String() }),
"loras": createMethodFilter({ response: {
GET: createEndpoint( 200: t.Null(),
{ query: null, body: null }, 401: t.Literal("Must be logged in"),
403: t.Literal("Must be an admin"),
},
},
)
.get(
"/:workerId/loras",
async ({ params }) => { async ({ params }) => {
const workerInstance = await workerInstanceStore.getById(params.workerId!); const workerInstance = await workerInstanceStore.getById(params.workerId);
if (!workerInstance) { if (!workerInstance) {
return { status: 404, body: { type: "text/plain", data: `Worker not found` } }; throw new NotFoundError("Worker not found");
} }
const sdClient = createOpenApiFetch<SdApi.paths>({ const sdClient = createOpenApiFetch<SdApi.paths>({
baseUrl: workerInstance.value.sdUrl, baseUrl: workerInstance.value.sdUrl,
@ -180,30 +183,32 @@ export const workersRoute = createPathFilter({
}); });
const lorasResponse = await sdClient.GET("/sdapi/v1/loras", {}); const lorasResponse = await sdClient.GET("/sdapi/v1/loras", {});
if (lorasResponse.error) { if (lorasResponse.error) {
return { throw new Error(
status: 500, `Loras request failed: ${lorasResponse["error"]}`,
body: { type: "text/plain", data: `Loras request failed: ${lorasResponse["error"]}` }, );
};
} }
const loras = (lorasResponse.data as Lora[]).map((lora) => ({ const loras = (lorasResponse.data as Lora[]).map((lora) => ({
name: lora.name, name: lora.name,
alias: lora.alias ?? null, alias: lora.alias ?? null,
})); }));
return { return loras;
status: 200,
body: { type: "application/json", data: loras },
};
}, },
), {
params: t.Object({ workerId: t.String() }),
response: t.Array(
t.Object({
name: t.String(),
alias: t.Nullable(t.String()),
}), }),
),
"models": createMethodFilter({ },
GET: createEndpoint( )
{ query: null, body: null }, .get(
"/:workerId/models",
async ({ params }) => { async ({ params }) => {
const workerInstance = await workerInstanceStore.getById(params.workerId!); const workerInstance = await workerInstanceStore.getById(params.workerId);
if (!workerInstance) { if (!workerInstance) {
return { status: 404, body: { type: "text/plain", data: `Worker not found` } }; throw new NotFoundError("Worker not found");
} }
const sdClient = createOpenApiFetch<SdApi.paths>({ const sdClient = createOpenApiFetch<SdApi.paths>({
baseUrl: workerInstance.value.sdUrl, baseUrl: workerInstance.value.sdUrl,
@ -211,29 +216,30 @@ export const workersRoute = createPathFilter({
}); });
const modelsResponse = await sdClient.GET("/sdapi/v1/sd-models", {}); const modelsResponse = await sdClient.GET("/sdapi/v1/sd-models", {});
if (modelsResponse.error) { if (modelsResponse.error) {
return { throw new Error(
status: 500, `Models request failed: ${modelsResponse["error"]}`,
body: { );
type: "text/plain",
data: `Models request failed: ${modelsResponse["error"]}`,
},
};
} }
const models = modelsResponse.data.map((model) => ({ const models = modelsResponse.data.map((model) => ({
title: model.title, title: model.title,
modelName: model.model_name, modelName: model.model_name,
hash: model.hash, hash: model.hash ?? null,
sha256: model.sha256, sha256: model.sha256 ?? null,
})); }));
return { return models;
status: 200,
body: { type: "application/json", data: models },
};
}, },
{
params: t.Object({ workerId: t.String() }),
response: t.Array(
t.Object({
title: t.String(),
modelName: t.String(),
hash: t.Nullable(t.String()),
sha256: t.Nullable(t.String()),
}),
), ),
}), },
}), );
});
export interface Lora { export interface Lora {
name: string; name: string;

View File

@ -1,24 +1,11 @@
import { Store } from "indexed_kv"; import { Static, t } from "elysia";
import { JsonSchema, jsonType } from "t_rest/server";
import { db } from "./db.ts"; import { db } from "./db.ts";
import { Tkv } from "../utils/Tkv.ts";
export const adminSchema = { export const adminSchema = t.Object({
type: "object", promotedBy: t.Nullable(t.Number()),
properties: {
tgUserId: { type: "number" },
promotedBy: { type: ["string", "null"] },
},
required: ["tgUserId", "promotedBy"],
} as const satisfies JsonSchema;
export type Admin = jsonType<typeof adminSchema>;
type AdminIndices = {
tgUserId: number;
};
export const adminStore = new Store<Admin, AdminIndices>(db, "adminUsers", {
indices: {
tgUserId: { getValue: (adminUser) => adminUser.tgUserId },
},
}); });
export type Admin = Static<typeof adminSchema>;
export const adminStore = new Tkv<["admins", number], Admin>(db);

View File

@ -1,51 +1,45 @@
import { Static, t } from "elysia";
import { Tkv } from "../utils/Tkv.ts";
import { db } from "./db.ts"; import { db } from "./db.ts";
import { JsonSchema, jsonType } from "t_rest/server";
export const configSchema = { export const defaultParamsSchema = t.Partial(t.Object({
type: "object", batch_size: t.Number(),
properties: { n_iter: t.Number(),
pausedReason: { type: ["string", "null"] }, width: t.Number(),
maxUserJobs: { type: "number" }, height: t.Number(),
maxJobs: { type: "number" }, steps: t.Number(),
defaultParams: { cfg_scale: t.Number(),
type: "object", sampler_name: t.String(),
properties: { negative_prompt: t.String(),
batch_size: { type: "number" }, }));
n_iter: { type: "number" },
width: { type: "number" },
height: { type: "number" },
steps: { type: "number" },
cfg_scale: { type: "number" },
sampler_name: { type: "string" },
negative_prompt: { type: "string" },
},
},
},
required: ["adminUsernames", "maxUserJobs", "maxJobs", "defaultParams"],
} as const satisfies JsonSchema;
export type Config = jsonType<typeof configSchema>; export type DefaultParams = Static<typeof defaultParamsSchema>;
export const configSchema = t.Object({
pausedReason: t.Nullable(t.String()),
maxUserJobs: t.Number(),
maxJobs: t.Number(),
defaultParams: defaultParamsSchema,
});
export type Config = Static<typeof configSchema>;
export const configStore = new Tkv<["config"], Config>(db);
const defaultConfig: Config = {
pausedReason: null,
maxUserJobs: Infinity,
maxJobs: Infinity,
defaultParams: {},
};
export async function getConfig(): Promise<Config> { export async function getConfig(): Promise<Config> {
const configEntry = await db.get<Config>(["config"]); const configEntry = await configStore.get(["config"]);
const config = configEntry?.value; return { ...defaultConfig, ...configEntry.value };
return {
pausedReason: config?.pausedReason ?? null,
maxUserJobs: config?.maxUserJobs ?? Infinity,
maxJobs: config?.maxJobs ?? Infinity,
defaultParams: config?.defaultParams ?? {},
};
} }
export async function setConfig(newConfig: Partial<Config>): Promise<void> { export async function setConfig<K extends keyof Config>(newConfig: Pick<Config, K>): Promise<void> {
const oldConfig = await getConfig(); const configEntry = await configStore.get(["config"]);
const config: Config = { const config = { ...defaultConfig, ...configEntry.value, ...newConfig };
pausedReason: newConfig.pausedReason === undefined await configStore.atomicSet(["config"], configEntry.versionstamp, config);
? oldConfig.pausedReason
: newConfig.pausedReason,
maxUserJobs: newConfig.maxUserJobs ?? oldConfig.maxUserJobs,
maxJobs: newConfig.maxJobs ?? oldConfig.maxJobs,
defaultParams: newConfig.defaultParams ?? oldConfig.defaultParams,
};
await db.set(["config"], config);
} }

View File

@ -1,25 +1,21 @@
import { hoursToMilliseconds, isSameDay, minutesToMilliseconds } from "date-fns"; import { hoursToMilliseconds, isSameDay, minutesToMilliseconds } from "date-fns";
import { UTCDateMini } from "date-fns/utc"; import { UTCDateMini } from "date-fns/utc";
import { Static, t } from "elysia";
import { info } from "std/log/mod.ts"; import { info } from "std/log/mod.ts";
import { JsonSchema, jsonType } from "t_rest/server";
import { db } from "./db.ts"; import { db } from "./db.ts";
import { generationStore } from "./generationStore.ts"; import { generationStore } from "./generationStore.ts";
import { kvMemoize } from "./kvMemoize.ts"; import { kvMemoize } from "../utils/kvMemoize.ts";
export const dailyStatsSchema = { export const dailyStatsSchema = t.Object({
type: "object", userIds: t.Array(t.Number()),
properties: { imageCount: t.Number(),
userIds: { type: "array", items: { type: "number" } }, stepCount: t.Number(),
imageCount: { type: "number" }, pixelCount: t.Number(),
stepCount: { type: "number" }, pixelStepCount: t.Number(),
pixelCount: { type: "number" }, timestamp: t.Number(),
pixelStepCount: { type: "number" }, });
timestamp: { type: "number" },
},
required: ["userIds", "imageCount", "stepCount", "pixelCount", "pixelStepCount", "timestamp"],
} as const satisfies JsonSchema;
export type DailyStats = jsonType<typeof dailyStatsSchema>; export type DailyStats = Static<typeof dailyStatsSchema>;
export const getDailyStats = kvMemoize( export const getDailyStats = kvMemoize(
db, db,

View File

@ -1,23 +1,16 @@
import { addDays } from "date-fns"; import { addDays } from "date-fns";
import { JsonSchema, jsonType } from "t_rest/server";
import { decodeTime } from "ulid"; import { decodeTime } from "ulid";
import { getDailyStats } from "./dailyStatsStore.ts"; import { getDailyStats } from "./dailyStatsStore.ts";
import { generationStore } from "./generationStore.ts"; import { generationStore } from "./generationStore.ts";
export const globalStatsSchema = { export interface GlobalStats {
type: "object", userIds: number[];
properties: { imageCount: number;
userIds: { type: "array", items: { type: "number" } }, stepCount: number;
imageCount: { type: "number" }, pixelCount: number;
stepCount: { type: "number" }, pixelStepCount: number;
pixelCount: { type: "number" }, timestamp: number;
pixelStepCount: { type: "number" }, }
timestamp: { type: "number" },
},
required: ["userIds", "imageCount", "stepCount", "pixelCount", "pixelStepCount", "timestamp"],
} as const satisfies JsonSchema;
export type GlobalStats = jsonType<typeof globalStatsSchema>;
export const globalStats: GlobalStats = await getGlobalStats(); export const globalStats: GlobalStats = await getGlobalStats();

View File

@ -1,21 +1,18 @@
import { JsonSchema, jsonType } from "t_rest/server"; import { Static, t } from "elysia";
import { kvMemoize } from "./kvMemoize.ts"; import { kvMemoize } from "../utils/kvMemoize.ts";
import { db } from "./db.ts"; import { db } from "./db.ts";
import { generationStore } from "./generationStore.ts"; import { generationStore } from "./generationStore.ts";
import { hoursToMilliseconds, isSameDay, minutesToMilliseconds } from "date-fns"; import { hoursToMilliseconds, isSameDay, minutesToMilliseconds } from "date-fns";
import { UTCDateMini } from "date-fns/utc"; import { UTCDateMini } from "date-fns/utc";
export const userDailyStatsSchema = { export const userDailyStatsSchema = t.Object({
type: "object", imageCount: t.Number(),
properties: { pixelCount: t.Number(),
imageCount: { type: "number" }, pixelStepCount: t.Number(),
pixelCount: { type: "number" }, timestamp: t.Number(),
timestamp: { type: "number" }, });
},
required: ["imageCount", "pixelCount", "timestamp"],
} as const satisfies JsonSchema;
export type UserDailyStats = jsonType<typeof userDailyStatsSchema>; export type UserDailyStats = Static<typeof userDailyStatsSchema>;
export const getUserDailyStats = kvMemoize( export const getUserDailyStats = kvMemoize(
db, db,
@ -23,6 +20,7 @@ export const getUserDailyStats = kvMemoize(
async (userId: number, year: number, month: number, day: number): Promise<UserDailyStats> => { async (userId: number, year: number, month: number, day: number): Promise<UserDailyStats> => {
let imageCount = 0; let imageCount = 0;
let pixelCount = 0; let pixelCount = 0;
let pixelStepCount = 0;
for await ( for await (
const generation of generationStore.listBy("fromId", { const generation of generationStore.listBy("fromId", {
@ -33,11 +31,15 @@ export const getUserDailyStats = kvMemoize(
) { ) {
imageCount++; imageCount++;
pixelCount += (generation.value.info?.width ?? 0) * (generation.value.info?.height ?? 0); pixelCount += (generation.value.info?.width ?? 0) * (generation.value.info?.height ?? 0);
pixelStepCount += (generation.value.info?.width ?? 0) *
(generation.value.info?.height ?? 0) *
(generation.value.info?.steps ?? 0);
} }
return { return {
imageCount, imageCount,
pixelCount, pixelCount,
pixelStepCount,
timestamp: Date.now(), timestamp: Date.now(),
}; };
}, },
@ -51,6 +53,7 @@ export const getUserDailyStats = kvMemoize(
: hoursToMilliseconds(24 * 7 + Math.random() * 24 * 7); : hoursToMilliseconds(24 * 7 + Math.random() * 24 * 7);
}, },
// should cache if the stats are non-zero // should cache if the stats are non-zero
shouldCache: (result) => result.imageCount > 0 || result.pixelCount > 0, shouldCache: (result) =>
result.imageCount > 0 || result.pixelCount > 0 || result.pixelStepCount > 0,
}, },
); );

View File

@ -1,38 +1,23 @@
import { minutesToMilliseconds } from "date-fns"; import { minutesToMilliseconds } from "date-fns";
import { Store } from "indexed_kv"; import { Store } from "indexed_kv";
import { info } from "std/log/mod.ts"; import { info } from "std/log/mod.ts";
import { JsonSchema, jsonType } from "t_rest/server"; import { Static, t } from "elysia";
import { db } from "./db.ts"; import { db } from "./db.ts";
import { generationStore } from "./generationStore.ts"; import { generationStore } from "./generationStore.ts";
import { kvMemoize } from "./kvMemoize.ts"; import { kvMemoize } from "../utils/kvMemoize.ts";
import { sortBy } from "std/collections/sort_by.ts"; import { sortBy } from "std/collections/sort_by.ts";
export const userStatsSchema = { export const userStatsSchema = t.Object({
type: "object", userId: t.Number(),
properties: { imageCount: t.Number(),
userId: { type: "number" }, stepCount: t.Number(),
imageCount: { type: "number" }, pixelCount: t.Number(),
stepCount: { type: "number" }, pixelStepCount: t.Number(),
pixelCount: { type: "number" }, tagCountMap: t.Record(t.String(), t.Number()),
pixelStepCount: { type: "number" }, timestamp: t.Number(),
tagCountMap: { });
type: "object",
additionalProperties: { type: "number" },
},
timestamp: { type: "number" },
},
required: [
"userId",
"imageCount",
"stepCount",
"pixelCount",
"pixelStepCount",
"tagCountMap",
"timestamp",
],
} as const satisfies JsonSchema;
export type UserStats = jsonType<typeof userStatsSchema>; export type UserStats = Static<typeof userStatsSchema>;
type UserStatsIndices = { type UserStatsIndices = {
userId: number; userId: number;

View File

@ -1,37 +1,23 @@
import { Store } from "indexed_kv"; import { Store } from "indexed_kv";
import { JsonSchema, jsonType } from "t_rest/server"; import { Static, t } from "elysia";
import { db } from "./db.ts"; import { db } from "./db.ts";
export const workerInstanceSchema = { export const workerInstanceSchema = t.Object({
type: "object", key: t.String(),
properties: { name: t.Nullable(t.String()),
// used for counting stats sdUrl: t.String(),
key: { type: "string" }, sdAuth: t.Nullable(t.Object({
// used for display user: t.String(),
name: { type: ["string", "null"] }, password: t.String(),
sdUrl: { type: "string" }, })),
sdAuth: { lastOnlineTime: t.Optional(t.Number()),
type: ["object", "null"], lastError: t.Optional(t.Object({
properties: { message: t.String(),
user: { type: "string" }, time: t.Number(),
password: { type: "string" }, })),
}, });
required: ["user", "password"],
},
lastOnlineTime: { type: "number" },
lastError: {
type: "object",
properties: {
message: { type: "string" },
time: { type: "number" },
},
required: ["message", "time"],
},
},
required: ["key", "name", "sdUrl", "sdAuth"],
} as const satisfies JsonSchema;
export type WorkerInstance = jsonType<typeof workerInstanceSchema>; export type WorkerInstance = Static<typeof workerInstanceSchema>;
export const workerInstanceStore = new Store<WorkerInstance>(db, "workerInstances", { export const workerInstanceStore = new Store<WorkerInstance>(db, "workerInstances", {
indices: {}, indices: {},

View File

@ -12,9 +12,9 @@ export async function broadcastCommand(ctx: CommandContext<ErisContext>) {
return ctx.reply("I don't know who you are."); return ctx.reply("I don't know who you are.");
} }
const [admin] = await adminStore.getBy("tgUserId", { value: ctx.from.id }); const adminEntry = await adminStore.get(["admins", ctx.from.id]);
if (!admin) { if (!adminEntry.versionstamp) {
return ctx.reply("Only a bot admin can use this command."); return ctx.reply("Only a bot admin can use this command.");
} }

View File

@ -39,9 +39,9 @@ async function txt2img(ctx: ErisContext, match: string, includeRepliedTo: boolea
return; return;
} }
const [admin] = await adminStore.getBy("tgUserId", { value: ctx.from.id }); const adminEntry = await adminStore.get(["admins", ctx.from.id]);
if (admin) { if (adminEntry.versionstamp) {
priority = 1; priority = 1;
} else { } else {
const jobs = await generationQueue.getAllJobs(); const jobs = await generationQueue.getAllJobs();

View File

@ -11,6 +11,9 @@
"async": "https://deno.land/x/async@v2.0.2/mod.ts", "async": "https://deno.land/x/async@v2.0.2/mod.ts",
"date-fns": "https://cdn.skypack.dev/date-fns@2.30.0?dts", "date-fns": "https://cdn.skypack.dev/date-fns@2.30.0?dts",
"date-fns/utc": "https://cdn.skypack.dev/@date-fns/utc@1.1.0?dts", "date-fns/utc": "https://cdn.skypack.dev/@date-fns/utc@1.1.0?dts",
"elysia": "https://esm.sh/elysia@0.7.21?dev",
"elysia/eden": "https://esm.sh/@elysiajs/eden@0.7.4?external=elysia&dev",
"elysia/swagger": "https://esm.sh/@elysiajs/swagger@0.7.4?external=elysia&dev",
"exifreader": "https://esm.sh/exifreader@4.14.1", "exifreader": "https://esm.sh/exifreader@4.14.1",
"file_type": "https://esm.sh/file-type@18.5.0", "file_type": "https://esm.sh/file-type@18.5.0",
"grammy": "https://lib.deno.dev/x/grammy@1/mod.ts", "grammy": "https://lib.deno.dev/x/grammy@1/mod.ts",
@ -40,8 +43,6 @@
"std/path/": "https://deno.land/std@0.204.0/path/", "std/path/": "https://deno.land/std@0.204.0/path/",
"swr": "https://esm.sh/swr@2.2.4?external=react&dev", "swr": "https://esm.sh/swr@2.2.4?external=react&dev",
"swr/mutation": "https://esm.sh/swr@2.2.4/mutation?external=react&dev", "swr/mutation": "https://esm.sh/swr@2.2.4/mutation?external=react&dev",
"t_rest/client": "https://esm.sh/ty-rest@0.4.1/client",
"t_rest/server": "https://esm.sh/ty-rest@0.4.1/server",
"twind/core": "https://esm.sh/@twind/core@1.1.3", "twind/core": "https://esm.sh/@twind/core@1.1.3",
"twind/preset-tailwind": "https://esm.sh/@twind/preset-tailwind@1.1.4", "twind/preset-tailwind": "https://esm.sh/@twind/preset-tailwind@1.1.4",
"ulid": "https://deno.land/x/ulid@v0.3.0/mod.ts" "ulid": "https://deno.land/x/ulid@v0.3.0/mod.ts"

View File

@ -299,10 +299,14 @@
"https://deno.land/x/swc@0.2.1/lib/deno_swc.generated.js": "a112eb5a4871bcbd5b660d3fd9d7afdd5cf2bb9e135eb9b04aceaa24d16481a0", "https://deno.land/x/swc@0.2.1/lib/deno_swc.generated.js": "a112eb5a4871bcbd5b660d3fd9d7afdd5cf2bb9e135eb9b04aceaa24d16481a0",
"https://deno.land/x/swc@0.2.1/mod.ts": "9e03f5daf4c2a25208e34e19ce3e997d2e23a5a11ee8c8ed58023b0e3626073f", "https://deno.land/x/swc@0.2.1/mod.ts": "9e03f5daf4c2a25208e34e19ce3e997d2e23a5a11ee8c8ed58023b0e3626073f",
"https://deno.land/x/ulid@v0.3.0/mod.ts": "f7ff065b66abd485051fc68af23becef6ccc7e81f7774d7fcfd894a4b2da1984", "https://deno.land/x/ulid@v0.3.0/mod.ts": "f7ff065b66abd485051fc68af23becef6ccc7e81f7774d7fcfd894a4b2da1984",
"https://esm.sh/@elysiajs/eden@0.7.4?external=elysia&dev": "28d477942e36cdeb3e57791a3acc1f52dd16378b1e639693897b21e98d7295e3",
"https://esm.sh/@elysiajs/swagger@0.7.4?dev": "78520881a756f6c3a69ccc1f306bc32e258c6e0e27f971f68231763fbafd303e",
"https://esm.sh/@elysiajs/swagger@0.7.4?external=elysia&dev": "9732dabca93af3dee2ed1781edb740f6e6bdbe88167cc6a03fa42bef3aadd315",
"https://esm.sh/@grammyjs/types@2.0.0": "5e5d1ae9f014cb64f0af36fb91f9d35414d670049b77367818a70cd62092b2ac", "https://esm.sh/@grammyjs/types@2.0.0": "5e5d1ae9f014cb64f0af36fb91f9d35414d670049b77367818a70cd62092b2ac",
"https://esm.sh/@grammyjs/types@2.12.1": "eebe448d3bf3d4fdaeacee50e31b9e3947ce965d2591f1036e5c0273cb7aec36", "https://esm.sh/@grammyjs/types@2.12.1": "eebe448d3bf3d4fdaeacee50e31b9e3947ce965d2591f1036e5c0273cb7aec36",
"https://esm.sh/@twind/core@1.1.3": "bf3e64c13de95b061a721831bf2aed322f6e7335848b06d805168c3212686c1d", "https://esm.sh/@twind/core@1.1.3": "bf3e64c13de95b061a721831bf2aed322f6e7335848b06d805168c3212686c1d",
"https://esm.sh/@twind/preset-tailwind@1.1.4": "29f5e4774c344ff08d2636e3d86382060a8b40d6bce1c158b803df1823c2804c", "https://esm.sh/@twind/preset-tailwind@1.1.4": "29f5e4774c344ff08d2636e3d86382060a8b40d6bce1c158b803df1823c2804c",
"https://esm.sh/elysia@0.7.21?dev": "6e954350858d5f2fd6c8e61dadf8d9989186f436ccdeb850606359d5e163298c",
"https://esm.sh/exifreader@4.14.1": "d0f21973393b0d1a6ed329dac8fcfb2f87ce47fe40b8172e205e7d6d85790bb6", "https://esm.sh/exifreader@4.14.1": "d0f21973393b0d1a6ed329dac8fcfb2f87ce47fe40b8172e205e7d6d85790bb6",
"https://esm.sh/file-type@18.5.0": "f01f6eddb05d365925545e26bd449f934dc042bead882b2795c35c4f48d690a3", "https://esm.sh/file-type@18.5.0": "f01f6eddb05d365925545e26bd449f934dc042bead882b2795c35c4f48d690a3",
"https://esm.sh/openapi-fetch@0.7.6": "43eff6df93e773801cb6ade02b0f47c05d0bfe2fb044adbf2b94fa74ff30d35b", "https://esm.sh/openapi-fetch@0.7.6": "43eff6df93e773801cb6ade02b0f47c05d0bfe2fb044adbf2b94fa74ff30d35b",
@ -321,6 +325,7 @@
"https://esm.sh/use-local-storage@3.0.0?external=react&dev": "4cf7fce754a9488940daa76051389421c6341420cae5b8c7d2401158ffe79ec0", "https://esm.sh/use-local-storage@3.0.0?external=react&dev": "4cf7fce754a9488940daa76051389421c6341420cae5b8c7d2401158ffe79ec0",
"https://esm.sh/v132/@twind/core@1.1.3/denonext/core.mjs": "c2618087a5d5cc406c7dc1079015f4d7cc874bee167f74e9945694896d907b6d", "https://esm.sh/v132/@twind/core@1.1.3/denonext/core.mjs": "c2618087a5d5cc406c7dc1079015f4d7cc874bee167f74e9945694896d907b6d",
"https://esm.sh/v132/@twind/preset-tailwind@1.1.4/denonext/preset-tailwind.mjs": "3cb9f5cde89e11cd2adad54ff264f62f5000ccb1694cd88874b1856eb2d8d7f7", "https://esm.sh/v132/@twind/preset-tailwind@1.1.4/denonext/preset-tailwind.mjs": "3cb9f5cde89e11cd2adad54ff264f62f5000ccb1694cd88874b1856eb2d8d7f7",
"https://esm.sh/v133/@elysiajs/swagger@0.7.4/denonext/swagger.development.mjs": "63cc67eee29123918283027744da23009fc3767088c513f8bfbfef945b7170d1",
"https://esm.sh/v133/@formatjs/ecma402-abstract@1.17.2/X-ZS9yZWFjdA/denonext/ecma402-abstract.development.mjs": "178a303e29d73369b4c7c1da5a18393c2baa8742a0e8a45be85f506c17f763d9", "https://esm.sh/v133/@formatjs/ecma402-abstract@1.17.2/X-ZS9yZWFjdA/denonext/ecma402-abstract.development.mjs": "178a303e29d73369b4c7c1da5a18393c2baa8742a0e8a45be85f506c17f763d9",
"https://esm.sh/v133/@formatjs/fast-memoize@2.2.0/X-ZS9yZWFjdA/denonext/fast-memoize.development.mjs": "4c027b3308490b65dc899f683b1ff9be8da4b7a2e1e32433ef03bcb8f0fdf821", "https://esm.sh/v133/@formatjs/fast-memoize@2.2.0/X-ZS9yZWFjdA/denonext/fast-memoize.development.mjs": "4c027b3308490b65dc899f683b1ff9be8da4b7a2e1e32433ef03bcb8f0fdf821",
"https://esm.sh/v133/@formatjs/icu-messageformat-parser@2.6.2/X-ZS9yZWFjdA/denonext/icu-messageformat-parser.development.mjs": "68c7a9be44aaa3e35bfe18668e17a2d4a465e11f59f3a1e025ee83fe1bd0b971", "https://esm.sh/v133/@formatjs/icu-messageformat-parser@2.6.2/X-ZS9yZWFjdA/denonext/icu-messageformat-parser.development.mjs": "68c7a9be44aaa3e35bfe18668e17a2d4a465e11f59f3a1e025ee83fe1bd0b971",
@ -330,14 +335,25 @@
"https://esm.sh/v133/@grammyjs/types@2.0.0/denonext/types.mjs": "7ee61bd0c55a152ea1ffaf3fbe63fce6c103ae836265b23290284d6ba0e3bc5b", "https://esm.sh/v133/@grammyjs/types@2.0.0/denonext/types.mjs": "7ee61bd0c55a152ea1ffaf3fbe63fce6c103ae836265b23290284d6ba0e3bc5b",
"https://esm.sh/v133/@grammyjs/types@2.12.1/denonext/types.mjs": "3636f7a1ca7fef89fa735d832b72193a834bc7f5250b6bf182544be53a6ab218", "https://esm.sh/v133/@grammyjs/types@2.12.1/denonext/types.mjs": "3636f7a1ca7fef89fa735d832b72193a834bc7f5250b6bf182544be53a6ab218",
"https://esm.sh/v133/@remix-run/router@1.9.0/X-ZS9yZWFjdA/denonext/router.development.mjs": "97f96f031a7298b0afbbadb23177559ee9b915314d7adf0b9c6a8d7f452c70e7", "https://esm.sh/v133/@remix-run/router@1.9.0/X-ZS9yZWFjdA/denonext/router.development.mjs": "97f96f031a7298b0afbbadb23177559ee9b915314d7adf0b9c6a8d7f452c70e7",
"https://esm.sh/v133/@sinclair/typebox@0.31.22/denonext/compiler.development.js": "94129b8b2f26f79bd1ec51f479776e7cdebe521f60bd2eae695634765959f7b9",
"https://esm.sh/v133/@sinclair/typebox@0.31.22/denonext/system.development.js": "e2c96ea22f15b9e79e8021b65ae62bfd1b4fd94176dd9c8fc1042fa014c64e9e",
"https://esm.sh/v133/@sinclair/typebox@0.31.22/denonext/typebox.development.mjs": "d5776065180eea03471f3f2c992a0cf8289219881c40b68270f543536f5ee029",
"https://esm.sh/v133/@sinclair/typebox@0.31.22/denonext/value.development.js": "41db30d8ba66c836ad5faf931f7ce38d15f943339847b8a7491014f8fe2be451",
"https://esm.sh/v133/client-only@0.0.1/X-ZS9yZWFjdA/denonext/client-only.development.mjs": "b7efaef2653f7f628d084e24a4d5a857c9cd1a5e5060d1d9957e185ee98c8a28", "https://esm.sh/v133/client-only@0.0.1/X-ZS9yZWFjdA/denonext/client-only.development.mjs": "b7efaef2653f7f628d084e24a4d5a857c9cd1a5e5060d1d9957e185ee98c8a28",
"https://esm.sh/v133/cookie@0.5.0/denonext/cookie.development.mjs": "04344caac1f8341ced6ec11d15b95a36dbda70a8ebb6a809b20b5912a5de2b8b",
"https://esm.sh/v133/crc-32@0.3.0/denonext/crc-32.mjs": "92bbd96cd5a92e45267cf4b3d3928b9355d16963da1ba740637fb10f1daca590", "https://esm.sh/v133/crc-32@0.3.0/denonext/crc-32.mjs": "92bbd96cd5a92e45267cf4b3d3928b9355d16963da1ba740637fb10f1daca590",
"https://esm.sh/v133/elysia@0.7.21/denonext/elysia.development.mjs": "4bf283f62b935737d33ab4e3e59195ba9cb0ea2fc2bac90c8e9fa00a44b5e575",
"https://esm.sh/v133/eventemitter3@5.0.1/denonext/eventemitter3.development.mjs": "e19a3e8d30d7564ce7b394636fc66ef273c6394bb6c5820b9a9bfba7ec4ac2dd",
"https://esm.sh/v133/exifreader@4.14.1/denonext/exifreader.mjs": "691e1c1d1337ccaf092bf39115fdac56bf69e93259d04bb03985e918202317ab", "https://esm.sh/v133/exifreader@4.14.1/denonext/exifreader.mjs": "691e1c1d1337ccaf092bf39115fdac56bf69e93259d04bb03985e918202317ab",
"https://esm.sh/v133/fast-decode-uri-component@1.0.1/denonext/fast-decode-uri-component.development.mjs": "004912e1f391fccf376cf58ff1ab06d6d4ed241cab9c7bed23756091bedbdc36",
"https://esm.sh/v133/fast-querystring@1.1.2/denonext/fast-querystring.development.mjs": "da06ef49d7e834dbac2b3b189de02c80e71cd5942b339de0011ab84aae0de0ff",
"https://esm.sh/v133/file-type@18.5.0/denonext/file-type.mjs": "785cac1bc363448647871e1b310422e01c9cfb7b817a68690710b786d3598311", "https://esm.sh/v133/file-type@18.5.0/denonext/file-type.mjs": "785cac1bc363448647871e1b310422e01c9cfb7b817a68690710b786d3598311",
"https://esm.sh/v133/hoist-non-react-statics@3.3.2/X-ZS9yZWFjdA/denonext/hoist-non-react-statics.development.mjs": "fcafac9e3c33810f18ecb43dfc32ce80efc88adc63d3f49fd7ada0665d2146c6", "https://esm.sh/v133/hoist-non-react-statics@3.3.2/X-ZS9yZWFjdA/denonext/hoist-non-react-statics.development.mjs": "fcafac9e3c33810f18ecb43dfc32ce80efc88adc63d3f49fd7ada0665d2146c6",
"https://esm.sh/v133/ieee754@1.2.1/denonext/ieee754.mjs": "9ec2806065f50afcd4cf3f3f2f38d93e777a92a5954dda00d219f57d4b24832f", "https://esm.sh/v133/ieee754@1.2.1/denonext/ieee754.mjs": "9ec2806065f50afcd4cf3f3f2f38d93e777a92a5954dda00d219f57d4b24832f",
"https://esm.sh/v133/inherits@2.0.4/denonext/inherits.mjs": "8095f3d6aea060c904fb24ae50f2882779c0acbe5d56814514c8b5153f3b4b3b", "https://esm.sh/v133/inherits@2.0.4/denonext/inherits.mjs": "8095f3d6aea060c904fb24ae50f2882779c0acbe5d56814514c8b5153f3b4b3b",
"https://esm.sh/v133/intl-messageformat@10.5.3/X-ZS9yZWFjdA/denonext/intl-messageformat.development.mjs": "d6b701c562c51ec4b4e1deb641c6623986abe304290bbb291e6404cb6a31dc41", "https://esm.sh/v133/intl-messageformat@10.5.3/X-ZS9yZWFjdA/denonext/intl-messageformat.development.mjs": "d6b701c562c51ec4b4e1deb641c6623986abe304290bbb291e6404cb6a31dc41",
"https://esm.sh/v133/lodash.clonedeep@4.5.0/denonext/lodash.clonedeep.development.mjs": "f44c863cb41bcd2714103a36d97e8eb8268f56070b5cd56dcfae26c556e6622e",
"https://esm.sh/v133/memoirist@0.1.4/denonext/memoirist.development.mjs": "e19f8379a684345ebcab9a688b0b188f29120f4bf1122588b779113cd1ec0e4e",
"https://esm.sh/v133/openapi-fetch@0.7.6/denonext/openapi-fetch.mjs": "1ec8ed23c9141c7f4e58de06f84525e310fe7dda1aeaf675c8edafb3d8292cfc", "https://esm.sh/v133/openapi-fetch@0.7.6/denonext/openapi-fetch.mjs": "1ec8ed23c9141c7f4e58de06f84525e310fe7dda1aeaf675c8edafb3d8292cfc",
"https://esm.sh/v133/peek-readable@5.0.0/denonext/peek-readable.mjs": "5e799ea86e9c501873f687eda9c891a75ed55ba666b5dd822eaa3d28a8a5f2b1", "https://esm.sh/v133/peek-readable@5.0.0/denonext/peek-readable.mjs": "5e799ea86e9c501873f687eda9c891a75ed55ba666b5dd822eaa3d28a8a5f2b1",
"https://esm.sh/v133/png-chunk-text@1.0.0/denonext/png-chunk-text.mjs": "e8bb89595ceab2603531693319da08a9dd90d51169437de47a73cf8bac7baa11", "https://esm.sh/v133/png-chunk-text@1.0.0/denonext/png-chunk-text.mjs": "e8bb89595ceab2603531693319da08a9dd90d51169437de47a73cf8bac7baa11",
@ -364,6 +380,10 @@
"https://esm.sh/v133/ty-rest@0.4.1/denonext/server.js": "00be1165ac96313b077629556a1587d4662f4e23bb0e815b945cc95cd3582370", "https://esm.sh/v133/ty-rest@0.4.1/denonext/server.js": "00be1165ac96313b077629556a1587d4662f4e23bb0e815b945cc95cd3582370",
"https://esm.sh/v133/use-local-storage@3.0.0/X-ZS9yZWFjdA/denonext/use-local-storage.development.mjs": "1fdc00893fe7dac56e95e2817e05d413b674f5cb5a1c6afd8994e25c9e2a56c8", "https://esm.sh/v133/use-local-storage@3.0.0/X-ZS9yZWFjdA/denonext/use-local-storage.development.mjs": "1fdc00893fe7dac56e95e2817e05d413b674f5cb5a1c6afd8994e25c9e2a56c8",
"https://esm.sh/v133/use-sync-external-store@1.2.0/X-ZS9yZWFjdA/denonext/shim.development.js": "5388baf48494f5abe76f8a4a30810c48e828b52f1298826aa9a3f3378e2b533f", "https://esm.sh/v133/use-sync-external-store@1.2.0/X-ZS9yZWFjdA/denonext/shim.development.js": "5388baf48494f5abe76f8a4a30810c48e828b52f1298826aa9a3f3378e2b533f",
"https://esm.sh/v133/util-deprecate@1.0.2/denonext/util-deprecate.mjs": "f69f67cf655c38428b0934e0f7c865c055834a87cc3866b629d6b2beb21005e9" "https://esm.sh/v133/util-deprecate@1.0.2/denonext/util-deprecate.mjs": "f69f67cf655c38428b0934e0f7c865c055834a87cc3866b629d6b2beb21005e9",
"https://esm.sh/v134/@elysiajs/eden@0.7.4/X-ZS9lbHlzaWE/denonext/eden.development.mjs": "c79c9f105d2b2062b882240272faa81cab1cbdde1113290d2d56c15ed9479986",
"https://esm.sh/v134/@elysiajs/swagger@0.7.4/X-ZS9lbHlzaWE/denonext/swagger.development.mjs": "4aa74e7b8108e9bacd7830c374ef24ee1b4100d65eef045bf6802ceaa3635554",
"https://esm.sh/v134/@sinclair/typebox@0.31.26/X-ZS9lbHlzaWE/denonext/typebox.development.mjs": "5f24db9ca594ccb61f2ae58df80a1f7690d21e117772e7b00babdb290c0747df",
"https://esm.sh/v134/lodash.clonedeep@4.5.0/X-ZS9lbHlzaWE/denonext/lodash.clonedeep.development.mjs": "f44c863cb41bcd2714103a36d97e8eb8268f56070b5cd56dcfae26c556e6622e"
} }
} }

View File

@ -11,18 +11,18 @@ export function AdminsPage(props: { sessionId: string | null }) {
const addDialogRef = useRef<HTMLDialogElement>(null); const addDialogRef = useRef<HTMLDialogElement>(null);
const getSession = useSWR( const getSession = useSWR(
sessionId ? ["sessions/{sessionId}", "GET", { params: { sessionId } }] as const : null, sessionId ? ["/sessions/:sessionId", { params: { sessionId } }] as const : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getUser = useSWR( const getUser = useSWR(
getSession.data?.userId getSession.data?.userId
? ["users/{userId}", "GET", { params: { userId: String(getSession.data.userId) } }] as const ? ["/users/:userId", { params: { userId: String(getSession.data.userId) } }] as const
: null, : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getAdmins = useSWR( const getAdmins = useSWR(
["admins", "GET", {}] as const, ["/admins", { method: "GET" }] as const,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
@ -32,14 +32,10 @@ export function AdminsPage(props: { sessionId: string | null }) {
<button <button
className="button-filled" className="button-filled"
onClick={() => { onClick={() => {
mutate( fetchApi("/admins/promote_self", {
(key) => Array.isArray(key) && key[0] === "admins", method: "POST",
async () =>
fetchApi("admins/promote_self", "POST", {
query: { sessionId: sessionId ?? "" }, query: { sessionId: sessionId ?? "" },
}).then(handleResponse), }).then(handleResponse).then(() => mutate(() => true));
{ populateCache: false },
);
}} }}
> >
Promote me to admin Promote me to admin
@ -50,7 +46,7 @@ export function AdminsPage(props: { sessionId: string | null }) {
? ( ? (
<ul className="flex flex-col gap-2"> <ul className="flex flex-col gap-2">
{getAdmins.data.map((admin) => ( {getAdmins.data.map((admin) => (
<AdminListItem key={admin.id} admin={admin} sessionId={sessionId} /> <AdminListItem key={admin.tgUserId} admin={admin} sessionId={sessionId} />
))} ))}
</ul> </ul>
) )
@ -99,20 +95,13 @@ function AddAdminDialog(props: {
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
const data = new FormData(e.target as HTMLFormElement); const data = new FormData(e.target as HTMLFormElement);
mutate( fetchApi("/admins", {
(key) => Array.isArray(key) && key[0] === "admins", method: "POST",
async () =>
fetchApi("admins", "POST", {
query: { sessionId: sessionId! }, query: { sessionId: sessionId! },
body: { body: {
type: "application/json",
data: {
tgUserId: Number(data.get("tgUserId") as string), tgUserId: Number(data.get("tgUserId") as string),
}, },
}, }).then(handleResponse).then(() => mutate(() => true));
}).then(handleResponse),
{ populateCache: false },
);
dialogRef.current?.close(); dialogRef.current?.close();
}} }}
> >
@ -152,17 +141,17 @@ function AdminListItem(props: { admin: AdminData; sessionId: string | null }) {
const deleteDialogRef = useRef<HTMLDialogElement>(null); const deleteDialogRef = useRef<HTMLDialogElement>(null);
const getAdminUser = useSWR( const getAdminUser = useSWR(
["users/{userId}", "GET", { params: { userId: String(admin.tgUserId) } }] as const, ["/users/:userId", { params: { userId: String(admin.tgUserId) } }] as const,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getSession = useSWR( const getSession = useSWR(
sessionId ? ["sessions/{sessionId}", "GET", { params: { sessionId } }] as const : null, sessionId ? ["/sessions/:sessionId", { params: { sessionId } }] as const : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getUser = useSWR( const getUser = useSWR(
getSession.data?.userId getSession.data?.userId
? ["users/{userId}", "GET", { params: { userId: String(getSession.data.userId) } }] as const ? ["/users/:userId", { params: { userId: String(getSession.data.userId) } }] as const
: null, : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
@ -170,7 +159,7 @@ function AdminListItem(props: { admin: AdminData; sessionId: string | null }) {
return ( return (
<li className="flex flex-col gap-2 rounded-md bg-zinc-100 dark:bg-zinc-800 p-2"> <li className="flex flex-col gap-2 rounded-md bg-zinc-100 dark:bg-zinc-800 p-2">
<p className="font-bold"> <p className="font-bold">
{getAdminUser.data?.first_name ?? admin.id} {getAdminUser.data?.last_name}{" "} {getAdminUser.data?.first_name ?? admin.tgUserId} {getAdminUser.data?.last_name}{" "}
{getAdminUser.data?.username {getAdminUser.data?.username
? ( ? (
<a href={`https://t.me/${getAdminUser.data.username}`} className="link"> <a href={`https://t.me/${getAdminUser.data.username}`} className="link">
@ -198,7 +187,7 @@ function AdminListItem(props: { admin: AdminData; sessionId: string | null }) {
)} )}
<DeleteAdminDialog <DeleteAdminDialog
dialogRef={deleteDialogRef} dialogRef={deleteDialogRef}
adminId={admin.id} adminId={admin.tgUserId}
sessionId={sessionId} sessionId={sessionId}
/> />
</li> </li>
@ -207,7 +196,7 @@ function AdminListItem(props: { admin: AdminData; sessionId: string | null }) {
function DeleteAdminDialog(props: { function DeleteAdminDialog(props: {
dialogRef: React.RefObject<HTMLDialogElement>; dialogRef: React.RefObject<HTMLDialogElement>;
adminId: string; adminId: number;
sessionId: string | null; sessionId: string | null;
}) { }) {
const { dialogRef, adminId, sessionId } = props; const { dialogRef, adminId, sessionId } = props;
@ -223,15 +212,12 @@ function DeleteAdminDialog(props: {
className="flex flex-col gap-4 p-4" className="flex flex-col gap-4 p-4"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
mutate(
(key) => Array.isArray(key) && key[0] === "admins", fetchApi("/admins/:adminId", {
async () => method: "DELETE",
fetchApi("admins/{adminId}", "DELETE", {
query: { sessionId: sessionId! }, query: { sessionId: sessionId! },
params: { adminId: adminId }, params: { adminId: String(adminId) },
}).then(handleResponse), }).then(handleResponse).then(() => mutate(() => true));
{ populateCache: false },
);
dialogRef.current?.close(); dialogRef.current?.close();
}} }}
> >

View File

@ -16,10 +16,12 @@ export function App() {
// initialize a new session when there is no session ID // initialize a new session when there is no session ID
useEffect(() => { useEffect(() => {
if (!sessionId) { if (!sessionId) {
fetchApi("sessions", "POST", {}).then(handleResponse).then((session) => { fetchApi("/sessions", { method: "POST" }).then((resp) => resp).then(handleResponse).then(
(session) => {
console.log("Initialized session", session.id); console.log("Initialized session", session.id);
setSessionId(session.id); setSessionId(session.id);
}); },
);
} }
}, [sessionId]); }, [sessionId]);

View File

@ -2,7 +2,7 @@ import React, { ReactNode } from "react";
import { NavLink } from "react-router-dom"; import { NavLink } from "react-router-dom";
import useSWR from "swr"; import useSWR from "swr";
import { cx } from "twind/core"; import { cx } from "twind/core";
import { fetchApi, handleResponse } from "./apiClient.ts"; import { API_URL, fetchApi, handleResponse } from "./apiClient.ts";
function NavTab(props: { to: string; children: ReactNode }) { function NavTab(props: { to: string; children: ReactNode }) {
return ( return (
@ -23,30 +23,42 @@ export function AppHeader(props: {
const { className, sessionId, onLogOut } = props; const { className, sessionId, onLogOut } = props;
const getSession = useSWR( const getSession = useSWR(
sessionId ? ["sessions/{sessionId}", "GET", { params: { sessionId } }] as const : null, sessionId ? ["/sessions/:sessionId", { method: "GET", params: { sessionId } }] as const : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
{ onError: () => onLogOut() }, { onError: () => onLogOut() },
); );
const getUser = useSWR( const getUser = useSWR(
getSession.data?.userId getSession.data?.userId
? ["users/{userId}", "GET", { params: { userId: String(getSession.data.userId) } }] as const ? ["/users/:userId", {
method: "GET",
params: { userId: String(getSession.data.userId) },
}] as const
: null, : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getBot = useSWR( const getBot = useSWR(
["bot", "GET", {}] as const, ["/bot", { method: "GET" }] as const,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getUserPhoto = useSWR( const getUserPhoto = useSWR(
getSession.data?.userId getSession.data?.userId
? ["users/{userId}/photo", "GET", { ? ["/users/:userId/photo", {
method: "GET",
params: { userId: String(getSession.data.userId) }, params: { userId: String(getSession.data.userId) },
}] as const }] as const
: null, : null,
(args) => fetchApi(...args).then(handleResponse).then((blob) => URL.createObjectURL(blob)), () =>
// elysia fetch can't download file
fetch(`${API_URL}/users/${getSession.data?.userId}/photo`)
.then((response) => {
if (!response.ok) throw new Error(response.statusText);
return response;
})
.then((response) => response.blob())
.then((blob) => blob ? URL.createObjectURL(blob) : null),
); );
return ( return (

View File

@ -7,7 +7,7 @@ import { fetchApi, handleResponse } from "./apiClient.ts";
export function QueuePage() { export function QueuePage() {
const getJobs = useSWR( const getJobs = useSWR(
["jobs", "GET", {}] as const, ["/jobs", {}] as const,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
{ refreshInterval: 2000 }, { refreshInterval: 2000 },
); );
@ -25,10 +25,10 @@ export function QueuePage() {
getJobs.data?.map((job) => ( getJobs.data?.map((job) => (
<li <li
className="flex items-baseline gap-2 bg-zinc-100 dark:bg-zinc-700 px-2 py-1 rounded-md" className="flex items-baseline gap-2 bg-zinc-100 dark:bg-zinc-700 px-2 py-1 rounded-md"
key={job.id.join("/")} key={job.id}
> >
<span className="">{job.place}.</span> <span className="">{job.place}.</span>
<span>{getFlagEmoji(job.state.from.language_code)}</span> <span>{getFlagEmoji(job.state.from.language_code ?? undefined)}</span>
<strong>{job.state.from.first_name} {job.state.from.last_name}</strong> <strong>{job.state.from.first_name} {job.state.from.last_name}</strong>
{job.state.from.username {job.state.from.username
? ( ? (

View File

@ -2,22 +2,23 @@ import React, { useState } from "react";
import useSWR from "swr"; import useSWR from "swr";
import { cx } from "twind/core"; import { cx } from "twind/core";
import { fetchApi, handleResponse } from "./apiClient.ts"; import { fetchApi, handleResponse } from "./apiClient.ts";
import { omitUndef } from "../utils/omitUndef.ts";
export function SettingsPage(props: { sessionId: string | null }) { export function SettingsPage(props: { sessionId: string | null }) {
const { sessionId } = props; const { sessionId } = props;
const getSession = useSWR( const getSession = useSWR(
sessionId ? ["sessions/{sessionId}", "GET", { params: { sessionId } }] as const : null, sessionId ? ["/sessions/:sessionId", { params: { sessionId } }] as const : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getUser = useSWR( const getUser = useSWR(
getSession.data?.userId getSession.data?.userId
? ["users/{userId}", "GET", { params: { userId: String(getSession.data.userId) } }] as const ? ["/users/:userId", { params: { userId: String( getSession.data.userId) } }] as const
: null, : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getParams = useSWR( const getParams = useSWR(
["settings/params", "GET", {}] as const, ["/settings/params", {}] as const,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const [newParams, setNewParams] = useState<Partial<typeof getParams.data>>({}); const [newParams, setNewParams] = useState<Partial<typeof getParams.data>>({});
@ -29,9 +30,10 @@ export function SettingsPage(props: { sessionId: string | null }) {
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
getParams.mutate(() => getParams.mutate(() =>
fetchApi("settings/params", "PATCH", { fetchApi("/settings/params", {
method: "PATCH",
query: { sessionId: sessionId ?? "" }, query: { sessionId: sessionId ?? "" },
body: { type: "application/json", data: newParams ?? {} }, body: omitUndef(newParams ?? {}),
}).then(handleResponse) }).then(handleResponse)
) )
.then(() => setNewParams({})) .then(() => setNewParams({}))

View File

@ -5,7 +5,7 @@ import { Counter } from "./Counter.tsx";
export function StatsPage() { export function StatsPage() {
const getGlobalStats = useSWR( const getGlobalStats = useSWR(
["stats", "GET", {}] as const, ["/stats", {}] as const,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
{ refreshInterval: 2_000 }, { refreshInterval: 2_000 },
); );

View File

@ -1,7 +1,7 @@
import React, { RefObject, useRef, useState } from "react"; import React, { RefObject, useRef } from "react";
import { FormattedRelativeTime } from "react-intl"; import { FormattedRelativeTime } from "react-intl";
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { WorkerData } from "../api/workersRoute.ts"; import { WorkerResponse } from "../api/workersRoute.ts";
import { Counter } from "./Counter.tsx"; import { Counter } from "./Counter.tsx";
import { fetchApi, handleResponse } from "./apiClient.ts"; import { fetchApi, handleResponse } from "./apiClient.ts";
@ -11,18 +11,18 @@ export function WorkersPage(props: { sessionId: string | null }) {
const addDialogRef = useRef<HTMLDialogElement>(null); const addDialogRef = useRef<HTMLDialogElement>(null);
const getSession = useSWR( const getSession = useSWR(
sessionId ? ["sessions/{sessionId}", "GET", { params: { sessionId } }] as const : null, sessionId ? ["/sessions/:sessionId", { params: { sessionId } }] as const : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getUser = useSWR( const getUser = useSWR(
getSession.data?.userId getSession.data?.userId
? ["users/{userId}", "GET", { params: { userId: String(getSession.data.userId) } }] as const ? ["/users/:userId", { params: { userId: String(getSession.data.userId) } }] as const
: null, : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getWorkers = useSWR( const getWorkers = useSWR(
["workers", "GET", {}] as const, ["/workers", { method: "GET" }] as const,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
{ refreshInterval: 5000 }, { refreshInterval: 5000 },
); );
@ -88,23 +88,16 @@ function AddWorkerDialog(props: {
const user = data.get("user") as string; const user = data.get("user") as string;
const password = data.get("password") as string; const password = data.get("password") as string;
console.log(key, name, user, password); console.log(key, name, user, password);
mutate( fetchApi("/workers", {
(key) => Array.isArray(key) && key[0] === "workers", method: "POST",
async () =>
fetchApi("workers", "POST", {
query: { sessionId: sessionId! }, query: { sessionId: sessionId! },
body: { body: {
type: "application/json",
data: {
key, key,
name: name || null, name: name || null,
sdUrl, sdUrl,
sdAuth: user && password ? { user, password } : null, sdAuth: user && password ? { user, password } : null,
}, },
}, }).then(handleResponse).then(() => mutate(() => true));
}).then(handleResponse),
{ populateCache: false },
);
dialogRef.current?.close(); dialogRef.current?.close();
}} }}
> >
@ -190,7 +183,7 @@ function AddWorkerDialog(props: {
} }
function WorkerListItem(props: { function WorkerListItem(props: {
worker: WorkerData; worker: WorkerResponse;
sessionId: string | null; sessionId: string | null;
}) { }) {
const { worker, sessionId } = props; const { worker, sessionId } = props;
@ -198,12 +191,12 @@ function WorkerListItem(props: {
const deleteDialogRef = useRef<HTMLDialogElement>(null); const deleteDialogRef = useRef<HTMLDialogElement>(null);
const getSession = useSWR( const getSession = useSWR(
sessionId ? ["sessions/{sessionId}", "GET", { params: { sessionId } }] as const : null, sessionId ? ["/sessions/:sessionId", { params: { sessionId } }] as const : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
const getUser = useSWR( const getUser = useSWR(
getSession.data?.userId getSession.data?.userId
? ["users/{userId}", "GET", { params: { userId: String(getSession.data.userId) } }] as const ? ["/users/:userId", { params: { userId: String(getSession.data.userId) } }] as const
: null, : null,
(args) => fetchApi(...args).then(handleResponse), (args) => fetchApi(...args).then(handleResponse),
); );
@ -296,21 +289,14 @@ function EditWorkerDialog(props: {
const user = data.get("user") as string; const user = data.get("user") as string;
const password = data.get("password") as string; const password = data.get("password") as string;
console.log(user, password); console.log(user, password);
mutate( fetchApi("/workers/:workerId", {
(key) => Array.isArray(key) && key[0] === "workers", method: "PATCH",
async () =>
fetchApi("workers/{workerId}", "PATCH", {
params: { workerId: workerId }, params: { workerId: workerId },
query: { sessionId: sessionId! }, query: { sessionId: sessionId! },
body: { body: {
type: "application/json",
data: {
sdAuth: user && password ? { user, password } : null, sdAuth: user && password ? { user, password } : null,
}, },
}, }).then(handleResponse).then(() => mutate(() => true));
}).then(handleResponse),
{ populateCache: false },
);
dialogRef.current?.close(); dialogRef.current?.close();
}} }}
> >
@ -371,15 +357,11 @@ function DeleteWorkerDialog(props: {
className="flex flex-col gap-4 p-4" className="flex flex-col gap-4 p-4"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
mutate( fetchApi("/workers/:workerId", {
(key) => Array.isArray(key) && key[0] === "workers", method: "DELETE",
async () =>
fetchApi("workers/{workerId}", "DELETE", {
params: { workerId: workerId }, params: { workerId: workerId },
query: { sessionId: sessionId! }, query: { sessionId: sessionId! },
}).then(handleResponse), }).then(handleResponse).then(() => mutate(() => true));
{ populateCache: false },
);
dialogRef.current?.close(); dialogRef.current?.close();
}} }}
> >

View File

@ -1,15 +1,19 @@
import { createFetcher, Output } from "t_rest/client"; import { edenFetch } from "elysia/eden";
import { ApiHandler } from "../api/serveApi.ts"; import { Api } from "../api/serveApi.ts";
export const fetchApi = createFetcher<ApiHandler>({ export const API_URL = "/api";
baseUrl: `${location.origin}/api/`,
});
export function handleResponse<T extends Output>( export const fetchApi = edenFetch<Api>(API_URL);
export function handleResponse<
T extends
| { data: unknown; error: null }
| { data: null; error: { status: number; value: unknown } },
>(
response: T, response: T,
): (T & { status: 200 })["body"]["data"] { ): (T & { error: null })["data"] {
if (response.status !== 200) { if (response.error) {
throw new Error(String(response.body.data)); throw new Error(`${response.error?.status}: ${response.error?.value}`);
} }
return response.body.data; return response.data;
} }

76
utils/Tkv.ts Normal file
View File

@ -0,0 +1,76 @@
export type TkvEntry<K extends Deno.KvKey, T> = {
key: readonly [...K];
value: T;
versionstamp: string;
};
export type TkvEntryMaybe<K extends Deno.KvKey, T> = TkvEntry<K, T> | {
key: readonly [...K];
value: null;
versionstamp: null;
};
export type TkvListSelector<K extends Deno.KvKey> =
| { prefix: KvKeyPrefix<K> }
| { prefix: KvKeyPrefix<K>; start: readonly [...K] }
| { prefix: KvKeyPrefix<K>; end: readonly [...K] }
| { start: readonly [...K]; end: readonly [...K] };
export type KvKeyPrefix<Key extends Deno.KvKey> = Key extends readonly [infer Prefix, ...infer Rest]
? readonly [Prefix] | readonly [Prefix, ...Rest]
: never;
/**
* Typed wrapper for {@link Deno.Kv}
*/
export class Tkv<K extends Deno.KvKey, T> {
constructor(readonly db: Deno.Kv) {}
get(
key: readonly [...K],
options: Parameters<Deno.Kv["get"]>[1] = {},
): Promise<TkvEntryMaybe<K, T>> {
return this.db.get<T>(key, options) as any;
}
set(
key: readonly [...K],
value: T,
options: Parameters<Deno.Kv["set"]>[2] = {},
): ReturnType<Deno.Kv["set"]> {
return this.db.set(key, value, options);
}
atomicSet(
key: readonly [...K],
versionstamp: Parameters<Deno.AtomicOperation["check"]>[0]["versionstamp"],
value: T,
options: Parameters<Deno.AtomicOperation["set"]>[2] = {},
): ReturnType<Deno.AtomicOperation["commit"]> {
return this.db.atomic()
.check({ key, versionstamp })
.set(key, value, options)
.commit();
}
delete(key: readonly [...K]): ReturnType<Deno.Kv["delete"]> {
return this.db.delete(key);
}
atomicDelete(
key: readonly [...K],
versionstamp: Parameters<Deno.AtomicOperation["check"]>[0]["versionstamp"],
): ReturnType<Deno.AtomicOperation["commit"]> {
return this.db.atomic()
.check({ key, versionstamp })
.delete(key)
.commit();
}
list(
selector: TkvListSelector<K>,
options: Parameters<Deno.Kv["list"]>[1] = {},
): AsyncIterableIterator<TkvEntry<K, T>> {
return this.db.list<T>(selector as Deno.KvListSelector, options) as any;
}
}