forked from Mike/freno-dev
continued migration
This commit is contained in:
493
src/server/api/routers/lineage/auth.ts
Normal file
493
src/server/api/routers/lineage/auth.ts
Normal file
@@ -0,0 +1,493 @@
|
||||
import { createTRPCRouter, publicProcedure } from "../../utils";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
LineageConnectionFactory,
|
||||
LineageDBInit,
|
||||
hashPassword,
|
||||
checkPassword,
|
||||
sendEmailVerification,
|
||||
LINEAGE_JWT_EXPIRY,
|
||||
} from "~/server/utils";
|
||||
import { env } from "~/env/server";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { SignJWT, jwtVerify } from "jose";
|
||||
import { LibsqlError } from "@libsql/client/web";
|
||||
import { createClient as createAPIClient } from "@tursodatabase/api";
|
||||
|
||||
export const lineageAuthRouter = createTRPCRouter({
|
||||
emailLogin: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { email, password } = input;
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
const query = `SELECT * FROM User WHERE email = ? AND provider = ? LIMIT 1`;
|
||||
const params = [email, "email"];
|
||||
const res = await conn.execute({ sql: query, args: params });
|
||||
|
||||
if (res.rows.length === 0) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid Credentials",
|
||||
});
|
||||
}
|
||||
|
||||
const user = res.rows[0];
|
||||
|
||||
if (user.email_verified === 0) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Email not yet verified!",
|
||||
});
|
||||
}
|
||||
|
||||
const valid = await checkPassword(password, user.password_hash as string);
|
||||
if (!valid) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid Credentials",
|
||||
});
|
||||
}
|
||||
|
||||
const secret = new TextEncoder().encode(env.JWT_SECRET_KEY);
|
||||
const token = await new SignJWT({ userId: user.id, email: user.email })
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setExpirationTime(LINEAGE_JWT_EXPIRY)
|
||||
.sign(secret);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Login successful",
|
||||
token,
|
||||
email,
|
||||
};
|
||||
}),
|
||||
|
||||
emailRegistration: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
password_conf: z.string().min(8),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { email, password, password_conf } = input;
|
||||
|
||||
if (password !== password_conf) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Password mismatch",
|
||||
});
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
const conn = LineageConnectionFactory();
|
||||
const userCreationQuery = `
|
||||
INSERT INTO User (email, provider, password_hash)
|
||||
VALUES (?, ?, ?)
|
||||
`;
|
||||
const params = [email, "email", passwordHash];
|
||||
|
||||
try {
|
||||
await conn.execute({ sql: userCreationQuery, args: params });
|
||||
|
||||
const emailResult = await sendEmailVerification(email);
|
||||
if (emailResult.success && emailResult.messageId) {
|
||||
return {
|
||||
success: true,
|
||||
message: "Email verification sent!",
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: emailResult.message || "Failed to send verification email",
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
if (e instanceof LibsqlError && e.code === "SQLITE_CONSTRAINT") {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "User already exists",
|
||||
});
|
||||
}
|
||||
if (e instanceof TRPCError) throw e;
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "An error occurred while creating the user",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
emailVerification: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
token: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { email: userEmail, token } = input;
|
||||
|
||||
let conn;
|
||||
let dbName;
|
||||
let dbToken;
|
||||
|
||||
try {
|
||||
const secret = new TextEncoder().encode(env.JWT_SECRET_KEY);
|
||||
const { payload } = await jwtVerify(token, secret);
|
||||
|
||||
if (payload.email !== userEmail) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Authentication failed: email mismatch",
|
||||
});
|
||||
}
|
||||
|
||||
conn = LineageConnectionFactory();
|
||||
const dbInit = await LineageDBInit();
|
||||
dbName = dbInit.dbName;
|
||||
dbToken = dbInit.token;
|
||||
|
||||
const query = `UPDATE User SET email_verified = ?, database_name = ?, database_token = ? WHERE email = ?`;
|
||||
const queryParams = [true, dbName, dbToken, userEmail];
|
||||
const res = await conn.execute({ sql: query, args: queryParams });
|
||||
|
||||
if (res.rowsAffected === 0) {
|
||||
throw new Error("User not found or update failed");
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
"Email verification success. You may close this window and sign in within the app.",
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("Error in email verification:", err);
|
||||
|
||||
if (dbName) {
|
||||
try {
|
||||
const turso = createAPIClient({
|
||||
org: "mikefreno",
|
||||
token: env.TURSO_DB_API_TOKEN,
|
||||
});
|
||||
await turso.databases.delete(dbName);
|
||||
console.log(`Database ${dbName} deleted due to error`);
|
||||
} catch (deleteErr) {
|
||||
console.error("Error deleting database:", deleteErr);
|
||||
}
|
||||
}
|
||||
|
||||
if (conn) {
|
||||
try {
|
||||
await conn.execute({
|
||||
sql: `UPDATE User SET email_verified = ?, database_name = ?, database_token = ? WHERE email = ?`,
|
||||
args: [false, null, null, userEmail],
|
||||
});
|
||||
console.log("User table update reverted");
|
||||
} catch (revertErr) {
|
||||
console.error("Error reverting User table update:", revertErr);
|
||||
}
|
||||
}
|
||||
|
||||
if (err instanceof TRPCError) throw err;
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message:
|
||||
"Authentication failed: An error occurred during email verification. Please try again.",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
refreshVerification: publicProcedure
|
||||
.input(z.object({ email: z.string().email() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const { email } = input;
|
||||
const conn = LineageConnectionFactory();
|
||||
const query = "SELECT * FROM User WHERE email = ?";
|
||||
const params = [email];
|
||||
|
||||
const res = await conn.execute({ sql: query, args: params });
|
||||
|
||||
if (res.rows.length === 0 || res.rows[0].email_verified) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Invalid Request",
|
||||
});
|
||||
}
|
||||
|
||||
const emailResult = await sendEmailVerification(email);
|
||||
if (emailResult.success && emailResult.messageId) {
|
||||
return {
|
||||
success: true,
|
||||
message: "Email verification sent!",
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: emailResult.message || "Failed to send verification email",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
refreshToken: publicProcedure
|
||||
.input(z.object({ token: z.string() }))
|
||||
.query(async ({ input }) => {
|
||||
const { token } = input;
|
||||
|
||||
try {
|
||||
const secret = new TextEncoder().encode(env.JWT_SECRET_KEY);
|
||||
const { payload } = await jwtVerify(token, secret);
|
||||
|
||||
const newToken = await new SignJWT({
|
||||
userId: payload.userId,
|
||||
email: payload.email,
|
||||
})
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setExpirationTime(LINEAGE_JWT_EXPIRY)
|
||||
.sign(secret);
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
ok: true,
|
||||
valid: true,
|
||||
token: newToken,
|
||||
email: payload.email,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
googleRegistration: publicProcedure
|
||||
.input(z.object({ email: z.string().email() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const { email } = input;
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
|
||||
try {
|
||||
const checkUserQuery = "SELECT * FROM User WHERE email = ?";
|
||||
const checkUserResult = await conn.execute({
|
||||
sql: checkUserQuery,
|
||||
args: [email],
|
||||
});
|
||||
|
||||
if (checkUserResult.rows.length > 0) {
|
||||
const updateQuery = `
|
||||
UPDATE User
|
||||
SET provider = ?
|
||||
WHERE email = ?
|
||||
`;
|
||||
const updateRes = await conn.execute({
|
||||
sql: updateQuery,
|
||||
args: ["google", email],
|
||||
});
|
||||
|
||||
if (updateRes.rowsAffected !== 0) {
|
||||
return {
|
||||
success: true,
|
||||
message: "User information updated",
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "User update failed!",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let db_name;
|
||||
try {
|
||||
const { token, dbName } = await LineageDBInit();
|
||||
db_name = dbName;
|
||||
console.log("init success");
|
||||
const insertQuery = `
|
||||
INSERT INTO User (email, email_verified, provider, database_name, database_token)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`;
|
||||
await conn.execute({
|
||||
sql: insertQuery,
|
||||
args: [email, true, "google", dbName, token],
|
||||
});
|
||||
|
||||
console.log("insert success");
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "New user created",
|
||||
};
|
||||
} catch (error) {
|
||||
if (db_name) {
|
||||
const turso = createAPIClient({
|
||||
org: "mikefreno",
|
||||
token: env.TURSO_DB_API_TOKEN,
|
||||
});
|
||||
await turso.databases.delete(db_name);
|
||||
}
|
||||
console.error(error);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to create user",
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error in Google Sign-Up handler:", error);
|
||||
if (error instanceof TRPCError) throw error;
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "An error occurred while processing the request",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
appleRegistration: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.string().email().optional(),
|
||||
userString: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { email, userString } = input;
|
||||
|
||||
let dbName;
|
||||
let dbToken;
|
||||
const conn = LineageConnectionFactory();
|
||||
|
||||
try {
|
||||
let checkUserQuery = "SELECT * FROM User WHERE apple_user_string = ?";
|
||||
|
||||
let args: string[] = [userString];
|
||||
if (email) {
|
||||
args.push(email);
|
||||
checkUserQuery += " OR email = ?";
|
||||
}
|
||||
const checkUserResult = await conn.execute({
|
||||
sql: checkUserQuery,
|
||||
args: args,
|
||||
});
|
||||
|
||||
if (checkUserResult.rows.length > 0) {
|
||||
const setClauses = [];
|
||||
const values = [];
|
||||
|
||||
if (email) {
|
||||
setClauses.push("email = ?");
|
||||
values.push(email);
|
||||
}
|
||||
setClauses.push("provider = ?", "apple_user_string = ?");
|
||||
values.push("apple", userString);
|
||||
const whereClause = `WHERE apple_user_string = ?${
|
||||
email ? " OR email = ?" : ""
|
||||
}`;
|
||||
values.push(userString);
|
||||
if (email) {
|
||||
values.push(email);
|
||||
}
|
||||
|
||||
const updateQuery = `UPDATE User SET ${setClauses.join(
|
||||
", "
|
||||
)} ${whereClause}`;
|
||||
const updateRes = await conn.execute({
|
||||
sql: updateQuery,
|
||||
args: values,
|
||||
});
|
||||
|
||||
if (updateRes.rowsAffected !== 0) {
|
||||
return {
|
||||
success: true,
|
||||
message: "User information updated",
|
||||
email: checkUserResult.rows[0].email as string,
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "User update failed!",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const dbInit = await LineageDBInit();
|
||||
dbToken = dbInit.token;
|
||||
dbName = dbInit.dbName;
|
||||
|
||||
try {
|
||||
const insertQuery = `
|
||||
INSERT INTO User (email, email_verified, apple_user_string, provider, database_name, database_token)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`;
|
||||
await conn.execute({
|
||||
sql: insertQuery,
|
||||
args: [email, true, userString, "apple", dbName, dbToken],
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "New user created",
|
||||
dbName,
|
||||
dbToken,
|
||||
};
|
||||
} catch (error) {
|
||||
if (dbName) {
|
||||
const turso = createAPIClient({
|
||||
org: "mikefreno",
|
||||
token: env.TURSO_DB_API_TOKEN,
|
||||
});
|
||||
await turso.databases.delete(dbName);
|
||||
}
|
||||
console.error(error);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to create user",
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (dbName) {
|
||||
try {
|
||||
const turso = createAPIClient({
|
||||
org: "mikefreno",
|
||||
token: env.TURSO_DB_API_TOKEN,
|
||||
});
|
||||
await turso.databases.delete(dbName);
|
||||
} catch (deleteErr) {
|
||||
console.error("Error deleting database:", deleteErr);
|
||||
}
|
||||
}
|
||||
console.error("Error in Apple Sign-Up handler:", error);
|
||||
if (error instanceof TRPCError) throw error;
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "An error occurred while processing the request",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
appleGetEmail: publicProcedure
|
||||
.input(z.object({ userString: z.string() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const { userString } = input;
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
const query = "SELECT * FROM User WHERE apple_user_string = ?";
|
||||
const res = await conn.execute({ sql: query, args: [userString] });
|
||||
|
||||
if (res.rows.length > 0) {
|
||||
return { success: true, email: res.rows[0].email as string };
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "User not found",
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
393
src/server/api/routers/lineage/database.ts
Normal file
393
src/server/api/routers/lineage/database.ts
Normal file
@@ -0,0 +1,393 @@
|
||||
import { createTRPCRouter, publicProcedure } from "../../utils";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
LineageConnectionFactory,
|
||||
validateLineageRequest,
|
||||
dumpAndSendDB,
|
||||
} from "~/server/utils";
|
||||
import { env } from "~/env/server";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { OAuth2Client } from "google-auth-library";
|
||||
import { jwtVerify } from "jose";
|
||||
|
||||
export const lineageDatabaseRouter = createTRPCRouter({
|
||||
credentials: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
provider: z.enum(["email", "google", "apple"]),
|
||||
authToken: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { email, provider, authToken } = input;
|
||||
|
||||
try {
|
||||
let valid_request = false;
|
||||
|
||||
if (provider === "email") {
|
||||
const secret = new TextEncoder().encode(env.JWT_SECRET_KEY);
|
||||
const { payload } = await jwtVerify(authToken, secret);
|
||||
if (payload.email === email) {
|
||||
valid_request = true;
|
||||
}
|
||||
} else if (provider === "google") {
|
||||
const CLIENT_ID = env.VITE_GOOGLE_CLIENT_ID_MAGIC_DELVE || env.NEXT_PUBLIC_GOOGLE_CLIENT_ID_MAGIC_DELVE;
|
||||
if (!CLIENT_ID) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Google client ID not configured",
|
||||
});
|
||||
}
|
||||
const client = new OAuth2Client(CLIENT_ID);
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: authToken,
|
||||
audience: CLIENT_ID,
|
||||
});
|
||||
if (ticket.getPayload()?.email === email) {
|
||||
valid_request = true;
|
||||
}
|
||||
} else {
|
||||
const conn = LineageConnectionFactory();
|
||||
const query = "SELECT * FROM User WHERE apple_user_string = ?";
|
||||
const res = await conn.execute({ sql: query, args: [authToken] });
|
||||
if (res.rows.length > 0 && res.rows[0].email === email) {
|
||||
valid_request = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (valid_request) {
|
||||
const conn = LineageConnectionFactory();
|
||||
const query = "SELECT * FROM User WHERE email = ? LIMIT 1";
|
||||
const params = [email];
|
||||
const res = await conn.execute({ sql: query, args: params });
|
||||
|
||||
if (res.rows.length === 1) {
|
||||
const user = res.rows[0];
|
||||
return {
|
||||
success: true,
|
||||
db_name: user.database_name as string,
|
||||
db_token: user.database_token as string,
|
||||
};
|
||||
}
|
||||
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "No user found",
|
||||
});
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid credentials",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof TRPCError) throw error;
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Authentication failed",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
deletionInit: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
db_name: z.string(),
|
||||
db_token: z.string(),
|
||||
authToken: z.string(),
|
||||
skip_cron: z.boolean().optional(),
|
||||
send_dump_target: z.string().email().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { email, db_name, db_token, authToken, skip_cron, send_dump_target } = input;
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
const res = await conn.execute({
|
||||
sql: `SELECT * FROM User WHERE email = ?`,
|
||||
args: [email],
|
||||
});
|
||||
const userRow = res.rows[0];
|
||||
|
||||
if (!userRow) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "User not found",
|
||||
});
|
||||
}
|
||||
|
||||
const valid = await validateLineageRequest({
|
||||
auth_token: authToken,
|
||||
userRow,
|
||||
});
|
||||
|
||||
if (!valid) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid Verification",
|
||||
});
|
||||
}
|
||||
|
||||
const { database_token, database_name } = userRow;
|
||||
|
||||
if (database_token !== db_token || database_name !== db_name) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Incorrect Verification",
|
||||
});
|
||||
}
|
||||
|
||||
if (skip_cron) {
|
||||
if (send_dump_target) {
|
||||
const dumpRes = await dumpAndSendDB({
|
||||
dbName: db_name,
|
||||
dbToken: db_token,
|
||||
sendTarget: send_dump_target,
|
||||
});
|
||||
|
||||
if (dumpRes.success) {
|
||||
const deleteRes = await fetch(
|
||||
`https://api.turso.tech/v1/organizations/mikefreno/databases/${db_name}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.TURSO_DB_API_TOKEN}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (deleteRes.ok) {
|
||||
await conn.execute({
|
||||
sql: `DELETE FROM User WHERE email = ?`,
|
||||
args: [email],
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
message: `Account and Database deleted, db dump sent to email: ${send_dump_target}`,
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to delete database",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: dumpRes.reason || "Failed to dump database",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const deleteRes = await fetch(
|
||||
`https://api.turso.tech/v1/organizations/mikefreno/databases/${db_name}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.TURSO_DB_API_TOKEN}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (deleteRes.ok) {
|
||||
await conn.execute({
|
||||
sql: `DELETE FROM User WHERE email = ?`,
|
||||
args: [email],
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
message: `Account and Database deleted`,
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to delete database",
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const insertRes = await conn.execute({
|
||||
sql: `INSERT INTO cron (email, db_name, db_token, send_dump_target) VALUES (?, ?, ?, ?)`,
|
||||
args: [email, db_name, db_token, send_dump_target],
|
||||
});
|
||||
|
||||
if (insertRes.rowsAffected > 0) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
message: `Deletion scheduled.`,
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: `Deletion not scheduled, due to server failure`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
deletionCheck: publicProcedure
|
||||
.input(z.object({ email: z.string().email() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const { email } = input;
|
||||
const conn = LineageConnectionFactory();
|
||||
|
||||
try {
|
||||
const res = await conn.execute({
|
||||
sql: `SELECT * FROM cron WHERE email = ?`,
|
||||
args: [email],
|
||||
});
|
||||
const cronRow = res.rows[0];
|
||||
|
||||
if (!cronRow) {
|
||||
return { status: 204, ok: true };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
created_at: cronRow.created_at as string,
|
||||
};
|
||||
} catch (e) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to check deletion status",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
deletionCancel: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
authToken: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { email, authToken } = input;
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
|
||||
const resUser = await conn.execute({
|
||||
sql: `SELECT * FROM User WHERE email = ?;`,
|
||||
args: [email],
|
||||
});
|
||||
|
||||
if (resUser.rows.length === 0) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "User not found.",
|
||||
});
|
||||
}
|
||||
|
||||
const userRow = resUser.rows[0];
|
||||
|
||||
const valid = await validateLineageRequest({
|
||||
auth_token: authToken,
|
||||
userRow,
|
||||
});
|
||||
|
||||
if (!valid) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid credentials for cancelation.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = await conn.execute({
|
||||
sql: `DELETE FROM cron WHERE email = ?;`,
|
||||
args: [email],
|
||||
});
|
||||
|
||||
if (result.rowsAffected > 0) {
|
||||
return {
|
||||
status: 200,
|
||||
ok: true,
|
||||
message: "Cron job(s) canceled successfully.",
|
||||
};
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "No cron job found for the given email.",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
deletionCron: publicProcedure.query(async () => {
|
||||
const conn = LineageConnectionFactory();
|
||||
const res = await conn.execute(
|
||||
`SELECT * FROM cron WHERE created_at <= datetime('now', '-1 day');`
|
||||
);
|
||||
|
||||
if (res.rows.length > 0) {
|
||||
const executed_ids: (number | string)[] = [];
|
||||
|
||||
for (const row of res.rows) {
|
||||
const { id, db_name, db_token, send_dump_target, email } = row;
|
||||
|
||||
if (send_dump_target) {
|
||||
const dumpRes = await dumpAndSendDB({
|
||||
dbName: db_name as string,
|
||||
dbToken: db_token as string,
|
||||
sendTarget: send_dump_target as string,
|
||||
});
|
||||
|
||||
if (dumpRes.success) {
|
||||
const deleteRes = await fetch(
|
||||
`https://api.turso.tech/v1/organizations/mikefreno/databases/${db_name}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.TURSO_DB_API_TOKEN}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (deleteRes.ok) {
|
||||
await conn.execute({
|
||||
sql: `DELETE FROM User WHERE email = ?`,
|
||||
args: [email],
|
||||
});
|
||||
executed_ids.push(id as number);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const deleteRes = await fetch(
|
||||
`https://api.turso.tech/v1/organizations/mikefreno/databases/${db_name}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.TURSO_DB_API_TOKEN}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (deleteRes.ok) {
|
||||
await conn.execute({
|
||||
sql: `DELETE FROM User WHERE email = ?`,
|
||||
args: [email],
|
||||
});
|
||||
executed_ids.push(id as number);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (executed_ids.length > 0) {
|
||||
const placeholders = executed_ids.map(() => "?").join(", ");
|
||||
const deleteQuery = `DELETE FROM cron WHERE id IN (${placeholders});`;
|
||||
await conn.execute({ sql: deleteQuery, args: executed_ids });
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
message:
|
||||
"Processed databases deleted and corresponding cron rows removed.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { status: 200, ok: true };
|
||||
}),
|
||||
});
|
||||
141
src/server/api/routers/lineage/json-service.ts
Normal file
141
src/server/api/routers/lineage/json-service.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { createTRPCRouter, publicProcedure } from "../../utils";
|
||||
|
||||
// Attack data imports
|
||||
import playerAttacks from "~/lineage-json/attack-route/playerAttacks.json";
|
||||
import mageBooks from "~/lineage-json/attack-route/mageBooks.json";
|
||||
import mageSpells from "~/lineage-json/attack-route/mageSpells.json";
|
||||
import necroBooks from "~/lineage-json/attack-route/necroBooks.json";
|
||||
import necroSpells from "~/lineage-json/attack-route/necroSpells.json";
|
||||
import rangerBooks from "~/lineage-json/attack-route/rangerBooks.json";
|
||||
import rangerSpells from "~/lineage-json/attack-route/rangerSpells.json";
|
||||
import paladinBooks from "~/lineage-json/attack-route/paladinBooks.json";
|
||||
import paladinSpells from "~/lineage-json/attack-route/paladinSpells.json";
|
||||
import summons from "~/lineage-json/attack-route/summons.json";
|
||||
|
||||
// Conditions data imports
|
||||
import conditions from "~/lineage-json/conditions-route/conditions.json";
|
||||
import debilitations from "~/lineage-json/conditions-route/debilitations.json";
|
||||
import sanityDebuffs from "~/lineage-json/conditions-route/sanityDebuffs.json";
|
||||
|
||||
// Dungeon data imports
|
||||
import dungeons from "~/lineage-json/dungeon-route/dungeons.json";
|
||||
import specialEncounters from "~/lineage-json/dungeon-route/specialEncounters.json";
|
||||
|
||||
// Enemy data imports
|
||||
import bosses from "~/lineage-json/enemy-route/bosses.json";
|
||||
import enemies from "~/lineage-json/enemy-route/enemy.json";
|
||||
import enemyAttacks from "~/lineage-json/enemy-route/enemyAttacks.json";
|
||||
|
||||
// Item data imports
|
||||
import arrows from "~/lineage-json/item-route/arrows.json";
|
||||
import bows from "~/lineage-json/item-route/bows.json";
|
||||
import foci from "~/lineage-json/item-route/foci.json";
|
||||
import hats from "~/lineage-json/item-route/hats.json";
|
||||
import junk from "~/lineage-json/item-route/junk.json";
|
||||
import melee from "~/lineage-json/item-route/melee.json";
|
||||
import robes from "~/lineage-json/item-route/robes.json";
|
||||
import wands from "~/lineage-json/item-route/wands.json";
|
||||
import ingredients from "~/lineage-json/item-route/ingredients.json";
|
||||
import storyItems from "~/lineage-json/item-route/storyItems.json";
|
||||
import artifacts from "~/lineage-json/item-route/artifacts.json";
|
||||
import shields from "~/lineage-json/item-route/shields.json";
|
||||
import bodyArmor from "~/lineage-json/item-route/bodyArmor.json";
|
||||
import helmets from "~/lineage-json/item-route/helmets.json";
|
||||
import suffix from "~/lineage-json/item-route/suffix.json";
|
||||
import prefix from "~/lineage-json/item-route/prefix.json";
|
||||
import potions from "~/lineage-json/item-route/potions.json";
|
||||
import poison from "~/lineage-json/item-route/poison.json";
|
||||
import staves from "~/lineage-json/item-route/staves.json";
|
||||
|
||||
// Misc data imports
|
||||
import activities from "~/lineage-json/misc-route/activities.json";
|
||||
import investments from "~/lineage-json/misc-route/investments.json";
|
||||
import jobs from "~/lineage-json/misc-route/jobs.json";
|
||||
import manaOptions from "~/lineage-json/misc-route/manaOptions.json";
|
||||
import otherOptions from "~/lineage-json/misc-route/otherOptions.json";
|
||||
import healthOptions from "~/lineage-json/misc-route/healthOptions.json";
|
||||
import sanityOptions from "~/lineage-json/misc-route/sanityOptions.json";
|
||||
import pvpRewards from "~/lineage-json/misc-route/pvpRewards.json";
|
||||
|
||||
export const lineageJsonServiceRouter = createTRPCRouter({
|
||||
attacks: publicProcedure.query(() => {
|
||||
return {
|
||||
ok: true,
|
||||
playerAttacks,
|
||||
mageBooks,
|
||||
mageSpells,
|
||||
necroBooks,
|
||||
necroSpells,
|
||||
rangerBooks,
|
||||
rangerSpells,
|
||||
paladinBooks,
|
||||
paladinSpells,
|
||||
summons,
|
||||
};
|
||||
}),
|
||||
|
||||
conditions: publicProcedure.query(() => {
|
||||
return {
|
||||
ok: true,
|
||||
conditions,
|
||||
debilitations,
|
||||
sanityDebuffs,
|
||||
};
|
||||
}),
|
||||
|
||||
dungeons: publicProcedure.query(() => {
|
||||
return {
|
||||
ok: true,
|
||||
dungeons,
|
||||
specialEncounters,
|
||||
};
|
||||
}),
|
||||
|
||||
enemies: publicProcedure.query(() => {
|
||||
return {
|
||||
ok: true,
|
||||
bosses,
|
||||
enemies,
|
||||
enemyAttacks,
|
||||
};
|
||||
}),
|
||||
|
||||
items: publicProcedure.query(() => {
|
||||
return {
|
||||
ok: true,
|
||||
arrows,
|
||||
bows,
|
||||
foci,
|
||||
hats,
|
||||
junk,
|
||||
melee,
|
||||
robes,
|
||||
wands,
|
||||
ingredients,
|
||||
storyItems,
|
||||
artifacts,
|
||||
shields,
|
||||
bodyArmor,
|
||||
helmets,
|
||||
suffix,
|
||||
prefix,
|
||||
potions,
|
||||
poison,
|
||||
staves,
|
||||
};
|
||||
}),
|
||||
|
||||
misc: publicProcedure.query(() => {
|
||||
return {
|
||||
ok: true,
|
||||
activities,
|
||||
investments,
|
||||
jobs,
|
||||
manaOptions,
|
||||
otherOptions,
|
||||
healthOptions,
|
||||
sanityOptions,
|
||||
pvpRewards,
|
||||
};
|
||||
}),
|
||||
});
|
||||
83
src/server/api/routers/lineage/maintenance.ts
Normal file
83
src/server/api/routers/lineage/maintenance.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { createTRPCRouter, adminProcedure } from "../../utils";
|
||||
import { LineageConnectionFactory } from "~/server/utils";
|
||||
import { env } from "~/env/server";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { createClient as createAPIClient } from "@tursodatabase/api";
|
||||
|
||||
const IGNORE = ["frenome", "magic-delve-conductor"];
|
||||
|
||||
export const lineageMaintenanceRouter = createTRPCRouter({
|
||||
findLooseDatabases: adminProcedure.query(async () => {
|
||||
const conn = LineageConnectionFactory();
|
||||
const query = "SELECT database_url FROM User WHERE database_url IS NOT NULL";
|
||||
|
||||
try {
|
||||
const res = await conn.execute(query);
|
||||
const turso = createAPIClient({
|
||||
org: "mikefreno",
|
||||
token: env.TURSO_DB_API_TOKEN,
|
||||
});
|
||||
const linkedDatabaseUrls = res.rows.map((row) => row.database_url);
|
||||
|
||||
const all_dbs = await turso.databases.list();
|
||||
const dbs_to_delete = all_dbs.filter((db) => {
|
||||
return !IGNORE.includes(db.name) && !linkedDatabaseUrls.includes(db.name);
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
looseDatabases: dbs_to_delete,
|
||||
count: dbs_to_delete.length,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Error finding loose databases:", e);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to find loose databases",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
cleanupExpiredDatabases: adminProcedure.query(async () => {
|
||||
const conn = LineageConnectionFactory();
|
||||
const query =
|
||||
"SELECT * FROM User WHERE datetime(db_destroy_date) < datetime('now');";
|
||||
|
||||
try {
|
||||
const res = await conn.execute(query);
|
||||
const turso = createAPIClient({
|
||||
org: "mikefreno",
|
||||
token: env.TURSO_DB_API_TOKEN,
|
||||
});
|
||||
|
||||
const deletedDatabases = [];
|
||||
|
||||
for (const row of res.rows) {
|
||||
const db_url = row.database_url;
|
||||
|
||||
try {
|
||||
await turso.databases.delete(db_url as string);
|
||||
const updateQuery =
|
||||
"UPDATE User SET database_url = ?, database_token = ?, db_destroy_date = ? WHERE id = ?";
|
||||
const params = [null, null, null, row.id];
|
||||
await conn.execute({ sql: updateQuery, args: params });
|
||||
deletedDatabases.push(db_url);
|
||||
} catch (deleteErr) {
|
||||
console.error(`Failed to delete database ${db_url}:`, deleteErr);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
deletedDatabases,
|
||||
count: deletedDatabases.length,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Error cleaning up expired databases:", e);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to cleanup expired databases",
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
95
src/server/api/routers/lineage/misc.ts
Normal file
95
src/server/api/routers/lineage/misc.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { createTRPCRouter, publicProcedure } from "../../utils";
|
||||
import { z } from "zod";
|
||||
import { LineageConnectionFactory } from "~/server/utils";
|
||||
import { env } from "~/env/server";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
export const lineageMiscRouter = createTRPCRouter({
|
||||
analytics: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
playerID: z.string(),
|
||||
dungeonProgression: z.record(z.unknown()),
|
||||
playerClass: z.string(),
|
||||
spellCount: z.number(),
|
||||
proficiencies: z.record(z.unknown()),
|
||||
jobs: z.record(z.unknown()),
|
||||
resistanceTable: z.record(z.unknown()),
|
||||
damageTable: z.record(z.unknown()),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const {
|
||||
playerID,
|
||||
dungeonProgression,
|
||||
playerClass,
|
||||
spellCount,
|
||||
proficiencies,
|
||||
jobs,
|
||||
resistanceTable,
|
||||
damageTable,
|
||||
} = input;
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
|
||||
try {
|
||||
const res = await conn.execute({
|
||||
sql: `
|
||||
INSERT OR REPLACE INTO Analytics
|
||||
(playerID, dungeonProgression, playerClass, spellCount, proficiencies, jobs, resistanceTable, damageTable)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
args: [
|
||||
playerID,
|
||||
JSON.stringify(dungeonProgression),
|
||||
playerClass,
|
||||
spellCount,
|
||||
JSON.stringify(proficiencies),
|
||||
JSON.stringify(jobs),
|
||||
JSON.stringify(resistanceTable),
|
||||
JSON.stringify(damageTable),
|
||||
],
|
||||
});
|
||||
|
||||
return { success: true, status: 200 };
|
||||
} catch (e) {
|
||||
console.error("Analytics error:", e);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to store analytics",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
tokens: publicProcedure
|
||||
.input(z.object({ token: z.string() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const { token } = input;
|
||||
|
||||
if (!token) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Missing token in body",
|
||||
});
|
||||
}
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
const query = "SELECT * FROM Token WHERE token = ?";
|
||||
const res = await conn.execute({ sql: query, args: [token] });
|
||||
|
||||
if (res.rows.length > 0) {
|
||||
const queryUpdate =
|
||||
"UPDATE Token SET last_updated_at = datetime('now') WHERE token = ?";
|
||||
const resUpdate = await conn.execute({ sql: queryUpdate, args: [token] });
|
||||
return { success: true, action: "updated", result: resUpdate };
|
||||
} else {
|
||||
const queryInsert = "INSERT INTO Token (token) VALUES (?)";
|
||||
const resInsert = await conn.execute({ sql: queryInsert, args: [token] });
|
||||
return { success: true, action: "inserted", result: resInsert };
|
||||
}
|
||||
}),
|
||||
|
||||
offlineSecret: publicProcedure.query(() => {
|
||||
return { secret: env.LINEAGE_OFFLINE_SERIALIZATION_SECRET };
|
||||
}),
|
||||
});
|
||||
229
src/server/api/routers/lineage/pvp.ts
Normal file
229
src/server/api/routers/lineage/pvp.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import { createTRPCRouter, publicProcedure } from "../../utils";
|
||||
import { z } from "zod";
|
||||
import { LineageConnectionFactory } from "~/server/utils";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const characterSchema = z.object({
|
||||
playerClass: z.string(),
|
||||
blessing: z.string().optional(),
|
||||
name: z.string(),
|
||||
maxHealth: z.number(),
|
||||
maxSanity: z.number(),
|
||||
maxMana: z.number(),
|
||||
baseManaRegen: z.number(),
|
||||
strength: z.number(),
|
||||
intelligence: z.number(),
|
||||
dexterity: z.number(),
|
||||
resistanceTable: z.string(),
|
||||
damageTable: z.string(),
|
||||
attackStrings: z.string(),
|
||||
knownSpells: z.string(),
|
||||
});
|
||||
|
||||
export const lineagePvpRouter = createTRPCRouter({
|
||||
registerCharacter: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
character: characterSchema,
|
||||
linkID: z.string(),
|
||||
pushToken: z.string().optional(),
|
||||
pushCurrentlyEnabled: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { character, linkID, pushToken, pushCurrentlyEnabled } = input;
|
||||
|
||||
try {
|
||||
const conn = LineageConnectionFactory();
|
||||
const res = await conn.execute({
|
||||
sql: `SELECT * FROM PvP_Characters WHERE linkID = ?`,
|
||||
args: [linkID],
|
||||
});
|
||||
|
||||
if (res.rows.length === 0) {
|
||||
await conn.execute({
|
||||
sql: `INSERT INTO PvP_Characters (
|
||||
linkID,
|
||||
blessing,
|
||||
playerClass,
|
||||
name,
|
||||
maxHealth,
|
||||
maxSanity,
|
||||
maxMana,
|
||||
baseManaRegen,
|
||||
strength,
|
||||
intelligence,
|
||||
dexterity,
|
||||
resistanceTable,
|
||||
damageTable,
|
||||
attackStrings,
|
||||
knownSpells,
|
||||
pushToken,
|
||||
pushCurrentlyEnabled
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
args: [
|
||||
linkID,
|
||||
character.blessing,
|
||||
character.playerClass,
|
||||
character.name,
|
||||
character.maxHealth,
|
||||
character.maxSanity,
|
||||
character.maxMana,
|
||||
character.baseManaRegen,
|
||||
character.strength,
|
||||
character.intelligence,
|
||||
character.dexterity,
|
||||
character.resistanceTable,
|
||||
character.damageTable,
|
||||
character.attackStrings,
|
||||
character.knownSpells,
|
||||
pushToken,
|
||||
pushCurrentlyEnabled,
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
winCount: 0,
|
||||
lossCount: 0,
|
||||
tokenRedemptionCount: 0,
|
||||
status: 201,
|
||||
};
|
||||
} else {
|
||||
await conn.execute({
|
||||
sql: `UPDATE PvP_Characters SET
|
||||
playerClass = ?,
|
||||
blessing = ?,
|
||||
name = ?,
|
||||
maxHealth = ?,
|
||||
maxSanity = ?,
|
||||
maxMana = ?,
|
||||
baseManaRegen = ?,
|
||||
strength = ?,
|
||||
intelligence = ?,
|
||||
dexterity = ?,
|
||||
resistanceTable = ?,
|
||||
damageTable = ?,
|
||||
attackStrings = ?,
|
||||
knownSpells = ?,
|
||||
pushToken = ?,
|
||||
pushCurrentlyEnabled = ?
|
||||
WHERE linkID = ?`,
|
||||
args: [
|
||||
character.playerClass,
|
||||
character.blessing,
|
||||
character.name,
|
||||
character.maxHealth,
|
||||
character.maxSanity,
|
||||
character.maxMana,
|
||||
character.baseManaRegen,
|
||||
character.strength,
|
||||
character.intelligence,
|
||||
character.dexterity,
|
||||
character.resistanceTable,
|
||||
character.damageTable,
|
||||
character.attackStrings,
|
||||
character.knownSpells,
|
||||
pushToken,
|
||||
pushCurrentlyEnabled,
|
||||
linkID,
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
winCount: res.rows[0].winCount as number,
|
||||
lossCount: res.rows[0].lossCount as number,
|
||||
tokenRedemptionCount: res.rows[0].tokenRedemptionCount as number,
|
||||
status: 200,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to register character",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
getOpponents: publicProcedure.query(async () => {
|
||||
const conn = LineageConnectionFactory();
|
||||
|
||||
try {
|
||||
const res = await conn.execute(
|
||||
`
|
||||
SELECT playerClass,
|
||||
blessing,
|
||||
name,
|
||||
maxHealth,
|
||||
maxSanity,
|
||||
maxMana,
|
||||
baseManaRegen,
|
||||
strength,
|
||||
intelligence,
|
||||
dexterity,
|
||||
resistanceTable,
|
||||
damageTable,
|
||||
attackStrings,
|
||||
knownSpells,
|
||||
linkID,
|
||||
winCount,
|
||||
lossCount
|
||||
FROM PvP_Characters
|
||||
ORDER BY RANDOM()
|
||||
LIMIT 3
|
||||
`
|
||||
);
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
characters: res.rows,
|
||||
status: 200,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to get opponents",
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
battleResult: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
winnerLinkID: z.string(),
|
||||
loserLinkID: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { winnerLinkID, loserLinkID } = input;
|
||||
|
||||
const conn = LineageConnectionFactory();
|
||||
|
||||
try {
|
||||
await conn.execute({
|
||||
sql: `
|
||||
UPDATE PvP_Characters
|
||||
SET
|
||||
winCount = winCount + CASE WHEN linkID = ? THEN 1 ELSE 0 END,
|
||||
lossCount = lossCount + CASE WHEN linkID = ? THEN 1 ELSE 0 END
|
||||
WHERE linkID IN (?, ?)
|
||||
`,
|
||||
args: [winnerLinkID, loserLinkID, winnerLinkID, loserLinkID],
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to record battle result",
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
Reference in New Issue
Block a user