60 lines
2.1 KiB
TypeScript
60 lines
2.1 KiB
TypeScript
"use server";
|
|
import { API_LINK, XUIApiLinks } from "@/lib/enum";
|
|
import { authFetch } from "@/lib/login";
|
|
import { getValidUrl } from "@/lib/url";
|
|
import { prisma } from "@/utils/prisma";
|
|
import { redis } from "@/utils/redis";
|
|
import { User } from "@prisma/client";
|
|
import { parse, validate } from "@telegram-apps/init-data-node";
|
|
import { ClientSettings, InboundResponse } from "./_dto/inbounds";
|
|
|
|
async function getInboundApi() {
|
|
const res = await authFetch(API_LINK + XUIApiLinks.GET_INBOUNDS);
|
|
const data: InboundResponse = await res.json();
|
|
const inbound = data.obj.find((inbound) => inbound.remark === "WS");
|
|
return inbound;
|
|
}
|
|
|
|
async function getUrlApi(email: string) {
|
|
const cachedInbound = await redis.get("inbound");
|
|
const inbound = cachedInbound ? JSON.parse(cachedInbound) : await getInboundApi();
|
|
if (!inbound) {
|
|
throw new Error("Inbound not found");
|
|
}
|
|
await redis.set("inbound", JSON.stringify(inbound), "EX", 3600);
|
|
const users: ClientSettings = JSON.parse(inbound.settings);
|
|
const user = users.clients.find((user) => user.email === email);
|
|
if (!user) {
|
|
throw new Error("User not found");
|
|
}
|
|
return { url: getValidUrl({ email, id: user.id }), expiryTime: user.expiryTime };
|
|
}
|
|
export async function getUrl(initData: string = "") {
|
|
try {
|
|
if (process.env.NODE_ENV === "production")
|
|
validate(initData, process.env.BOT_TOKEN || "", {
|
|
expiresIn: 3600,
|
|
});
|
|
const initDataParsed = parse(initData);
|
|
if (!initDataParsed.user) {
|
|
throw new Error("User not found");
|
|
}
|
|
const cachedUser = await redis.get(`user:${initDataParsed.user.id}`);
|
|
const users: User[] = cachedUser
|
|
? JSON.parse(cachedUser)
|
|
: await prisma.user.findMany({
|
|
where: {
|
|
tgId: initDataParsed.user.id.toString(),
|
|
},
|
|
});
|
|
if (!users.length) {
|
|
throw new Error("User not found");
|
|
}
|
|
await redis.set(`user:${initDataParsed.user.id}`, JSON.stringify(users), "EX", 60);
|
|
const usersUrl = await Promise.all(users.map(async (user) => await getUrlApi(user.email || "")));
|
|
return usersUrl;
|
|
} catch (e) {
|
|
throw e;
|
|
}
|
|
}
|