Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
936 changes: 533 additions & 403 deletions bun.lock

Large diffs are not rendered by default.

34 changes: 17 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,31 +31,31 @@
"db:studio": "bun drizzle-kit studio"
},
"dependencies": {
"@elysiajs/cors": "^1.2.0",
"@elysiajs/cors": "^1.4.1",
"discord.js": "^14.26.2",
"dotenv-flow": "^4.1.0",
"drizzle-orm": "^0.39.3",
"elysia": "^1.2.12",
"drizzle-orm": "^0.45.2",
"elysia": "^1.4.28",
"ms": "^2.1.3",
"redis": "^4.7.0",
"winston": "^3.17.0",
"zod": "^3.24.2"
"redis": "^5.11.0",
"winston": "^3.19.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@antfu/eslint-config": "^4.2.1",
"drizzle-kit": "^0.30.4",
"@antfu/eslint-config": "^8.1.1",
"@graphql-codegen/cli": "^6.2.1",
"@graphql-codegen/typescript": "^5.0.9",
"@graphql-codegen/typescript-operations": "^5.0.9",
"@graphql-codegen/typescript-resolvers": "^5.1.7",
"@types/bun": "^1.3.11",
"@types/dotenv-flow": "^3.3.3",
"@types/ms": "^2.1.0",
"@types/node-rsa": "^1.1.4",
"@graphql-codegen/cli": "^5.0.5",
"@graphql-codegen/typescript": "^4.1.3",
"@graphql-codegen/typescript-operations": "^4.4.1",
"@graphql-codegen/typescript-resolvers": "^4.4.2",
"@types/node": "^25.5.2",
"eslint": "^9.20.1",
"prettier": "^3.5.1",
"prettier-eslint": "^16.3.0",
"@types/node-rsa": "^1.1.4",
"drizzle-kit": "^0.31.10",
"eslint": "^10.2.0",
"prettier": "^3.8.1",
"prettier-eslint": "^16.4.2",
"typescript": "^6.0.2"
}
}
}
8 changes: 3 additions & 5 deletions src/api/controllers/info.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import path from "node:path";
import fs from "node:fs";
import { desc } from "drizzle-orm";
import { Elysia, t } from "elysia";
import { db, tables } from "#database/db";
import { getStats } from "#utils/botStats";

const srcFolder = path.join(import.meta.dir, "..", "..");
import { srcPath } from "#utils/paths";

export const infoController = new Elysia({
prefix: "/info",
Expand Down Expand Up @@ -53,7 +51,7 @@ export const infoController = new Elysia({
async ({ set }) => {
set.headers["content-type"] = "text/plain";
set.status = 200;
return fs.readFileSync(path.join(import.meta.dir, "..", "..", "RSA", "id_rsa.pub"), "utf-8");
return fs.readFileSync(srcPath("RSA", "id_rsa.pub"), "utf-8");
},
{ response: t.String(), }
)
Expand All @@ -75,7 +73,7 @@ export const infoController = new Elysia({
);

function readLogFile() {
const logPath = path.join(srcFolder, "logging", "logs.json");
const logPath = srcPath("logging", "logs.json");
const lines = fs.readFileSync(logPath, "utf-8").split("\n").filter(Boolean);
return lines.map((line) => JSON.parse(line));
}
12 changes: 5 additions & 7 deletions src/api/controllers/public.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import path from "node:path";
import fs from "node:fs";
import { Elysia, t } from "elysia";
import { RSA } from "#utils/rsaEncryption";
import { graphQLRequest } from "#utils/graphQLRequest";
import { srcPath } from "#utils/paths";
import { db } from "#database/db";
import { anilistUser } from "#database/models";
import { aniListUser } from "#database/models";
import { eq } from "drizzle-orm";

const srcFolder = path.join(import.meta.dir, "..", "..");

export const publicController = new Elysia({
prefix: "/public",
name: "api:public",
Expand All @@ -18,7 +16,7 @@ export const publicController = new Elysia({
async ({ set }) => {
set.headers["content-type"] = "text/plain";
set.status = 200;
return fs.readFileSync(path.join(srcFolder, "RSA", "id_rsa.pub"), "utf-8");
return fs.readFileSync(srcPath("RSA", "id_rsa.pub"), "utf-8");
},
{ response: t.String(), }
)
Expand All @@ -34,9 +32,9 @@ export const publicController = new Elysia({
const decryptedToken = await rsa.decrypt(encryptedToken);
const { Viewer: data } = (await graphQLRequest("Viewer", {}, decryptedToken)).data;
if (!data) return { message: "Invalid token" };
const existingUser = (await db.select().from(anilistUser).where(eq(anilistUser.discordId, discordId)).limit(1))[0];
const existingUser = (await db.select().from(aniListUser).where(eq(aniListUser.discordId, discordId)).limit(1))[0];
if (existingUser) return { message: "User already registered" };
await db.insert(anilistUser).values({ discordId, anilistToken: encryptedToken, anilistId: data.id });
await db.insert(aniListUser).values({ discordId, aniListToken: encryptedToken, aniListId: data.id });

console.log(`Registered ${discordId} as ${data.name}`);
set.status = 201;
Expand Down
4 changes: 2 additions & 2 deletions src/api/controllers/trigger.controller.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { execSync, spawnSync } from "child_process";
import { Elysia, t } from "elysia";
import { sqlite } from "#database/db";
import path from "path";
import fs from "fs";
import { srcPath } from "#utils/paths";

export const triggerController = new Elysia({
prefix: "/trigger",
Expand All @@ -27,7 +27,7 @@ export const triggerController = new Elysia({
.post(
"/wipe-logs",
async () => {
const logPath = path.join(import.meta.dir, "..", "..", "logging", "logs.json");
const logPath = srcPath("logging", "logs.json");
fs.writeFileSync(logPath, JSON.stringify([]), "utf8");
return { message: "Wiped all logs!" };
},
Expand Down
6 changes: 3 additions & 3 deletions src/checks/run.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import fs from 'node:fs'
import path from 'node:path'
import { Client, type Check } from "#structures/index";
import { srcPath } from "#utils/paths";

export async function runChecks(client: Client) {
// Flatten the array of checks
const checks: Check[] = (
await Promise.all(
fs
.readdirSync(path.join(import.meta.dir))
.readdirSync(srcPath("checks"))
.filter(file => file.endsWith('.ts') && file !== 'run.ts')
.map(async (file) => {
const check = await import(path.join(import.meta.dir, file))
const check = await import(srcPath("checks", file))
return check.default
}),
)
Expand Down
4 changes: 2 additions & 2 deletions src/checks/verifyModules.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import fs from 'fs'
import path from 'path'
import { Check } from '#structures/index'
import { suffix } from "bun:ffi";
import { srcPath } from '#utils/paths'

const getLibPath = (name: string) => path.join(import.meta.dir, "../modules", `compiled/lib${name}.${suffix}`);
const getLibPath = (name: string) => srcPath("modules", "compiled", `lib${name}.${suffix}`);

const defaultModule = new Check({
name: 'FFI default module check',
Expand Down
6 changes: 3 additions & 3 deletions src/checks/verifyRSA.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import fs from 'fs'
import path from 'path'
import { RSA } from '#utils/rsaEncryption'
import { Check } from '#structures/index'
import { srcPath } from '#utils/paths'

const rsaPublicCheck = new Check({
name: 'RSA Public Key Check',
description: 'Ensure that RSA/id_rsa.pub is present and valid. This is required to encrypt sensitive content.',
optional: false,
run: () => {
if (!fs.existsSync(path.join(import.meta.dir, '..', 'RSA', 'id_rsa.pub')))
if (!fs.existsSync(srcPath('RSA', 'id_rsa.pub')))
throw new Error('RSA/id_rsa.pub does not exist.')
},
})
Expand All @@ -18,7 +18,7 @@ const rsaPrivateCheck = new Check({
description: 'Ensure that RSA/id_rsa is present and valid. This is required to decrypt sensitive content.',
optional: false,
run: () => {
if (!fs.existsSync(path.join(import.meta.dir, '..', 'RSA', 'id_rsa')))
if (!fs.existsSync(srcPath('RSA', 'id_rsa')))
throw new Error('RSA/id_rsa does not exist.')
},
})
Expand Down
6 changes: 3 additions & 3 deletions src/commands/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default {

const vars: UserQueryVariables = {
username,
userid: interaction.alID,
userid: interaction.aniListId,
};

if (!username && !vars.userid) throw new YuukoError("You need to provide a user to search for or link your AniList account. (check /auth help for more info)");
Expand All @@ -35,7 +35,7 @@ export default {
const uData = (
await graphQLRequest("User", {
username: vars.username,
}, interaction.ALtoken)
}, interaction.aniListToken)
).data.User;

if (!uData?.id) throw new YuukoError("Couldn't find user id.", { vars });
Expand All @@ -45,7 +45,7 @@ export default {

const {
data: { Activity: data },
} = await graphQLRequest("Activity", vars, interaction.ALtoken);
} = await graphQLRequest("Activity", vars, interaction.aniListToken);

if (!data) {
throw new YuukoError("Couldn't find any data.", { vars });
Expand Down
8 changes: 4 additions & 4 deletions src/commands/anime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,23 @@ export default {
const cacheData = (await redis.json.get(`_anime-${vars.aID}`)) as AnimeQuery["Media"] | null;

if (cacheData) {
if (interaction.alID) {
const _mediaListEntry = (await redis.json.get(`_user${interaction.alID}-ANIME`)) as Record<number, CacheEntry>;
if (interaction.aniListId) {
const _mediaListEntry = (await redis.json.get(`_user${interaction.aniListId}-ANIME`)) as Record<number, CacheEntry>;
if (!vars.aID) throw new YuukoError("No anime ID found");
const mediaListEntry = _mediaListEntry ? _mediaListEntry[vars.aID] : null;

if (mediaListEntry) cacheData.mediaListEntry = mediaListEntry;
}

client.logger.debug("User cache hit", { type: "commandDebug", command: name, seriesId: vars.aID, anilistId: interaction.alID })
client.logger.debug("User cache hit", { type: "commandDebug", command: name, seriesId: vars.aID, aniListId: interaction.aniListId })

return void handleData({ media: cacheData }, interaction, client, "ANIME");
}

const {
data: { Media: data },
headers,
} = await graphQLRequest("Anime", vars, interaction.ALtoken);
} = await graphQLRequest("Anime", vars, interaction.aniListToken);

if (!data) {
throw new YuukoError("No anime found.", { vars });
Expand Down
8 changes: 4 additions & 4 deletions src/commands/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { footer, getSubcommandOption, updateBotStats, YuukoError } from "#utils/index";
import { anilistUser } from "#database/models/anilistUser";
import { aniListUser } from "#database/models/anilistUser";
import type { Command } from "#structures/index";
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, MessageFlags, SlashCommandBuilder } from "discord.js";
import { db } from "#database/db";
Expand All @@ -23,7 +23,7 @@ export default {
run: async ({ interaction, client }, hookData): Promise<void> => {
const subcommandType = getSubcommandOption(interaction, hookData, "subcommandType", true) as "help" | "wipe";

db.query.anilistUser.findFirst({ where: (user, { eq }) => eq(user.discordId, interaction.user.id) });
db.query.aniListUser.findFirst({ where: (user, { eq }) => eq(user.discordId, interaction.user.id) });

if (subcommandType === "help") {
return void (await interaction.reply({
Expand All @@ -39,11 +39,11 @@ export default {
}));
}

const user = (await db.select().from(anilistUser).where(eq(anilistUser.discordId, interaction.user.id)).limit(1))[0];
const user = (await db.select().from(aniListUser).where(eq(aniListUser.discordId, interaction.user.id)).limit(1))[0];

if (subcommandType === "wipe") {
if (!user) throw new YuukoError("You don't have an AniList account bound to your Discord account.", { ephemeral: true })
await db.delete(anilistUser).where(eq(anilistUser.discordId, interaction.user.id));
await db.delete(aniListUser).where(eq(aniListUser.discordId, interaction.user.id));

await updateBotStats(client);
return void interaction.reply({
Expand Down
7 changes: 3 additions & 4 deletions src/commands/help.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { EmbedBuilder, SlashCommandBuilder, time } from "discord.js";
import fs from "fs";
import path from "path";
import { db, tables } from "#database/db";
import type { Command, CommandType } from "#structures/index";
import { buildPagination, CommandCategories } from "#utils/index";
import { buildPagination, CommandCategories, srcPath } from "#utils/index";
import { desc } from "drizzle-orm";

function generateHelpEmbeds(cmdsArr: string[], category: keyof typeof CommandCategories) {
Expand Down Expand Up @@ -53,7 +52,7 @@ export default {

run: async ({ interaction, client }): Promise<void> => {
// Require all files from the commands folder and fetch description
const cmds = fs.readdirSync(import.meta.dir).filter((x) => x.endsWith(".ts") && x != "help.ts");
const cmds = fs.readdirSync(srcPath("commands")).filter((x) => x.endsWith(".ts") && x != "help.ts");
const cmdsDesc = [];
const cmdGroups: Record<CommandType, Partial<Command>[]> = {
"User": [],
Expand All @@ -63,7 +62,7 @@ export default {
"Misc": [],
};
for (const cmd of cmds) {
const cmdEntry = (await import(path.join(import.meta.dir, cmd))).default as Command;
const cmdEntry = (await import(srcPath("commands", cmd))).default as Command;
if (cmdEntry.commandType === "Internal") continue;
if (!cmdGroups[cmdEntry.commandType]) cmdGroups[cmdEntry.commandType] = [];
cmdGroups[cmdEntry.commandType].push({ usage: cmdEntry.usage, name: cmdEntry.name, description: cmdEntry.description });
Expand Down
20 changes: 10 additions & 10 deletions src/commands/makeactivity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { footer, graphQLRequest, YuukoError, getAnilistUser } from "#utils/index";
import { footer, graphQLRequest, YuukoError, getAniListUser } from "#utils/index";
import { EmbedBuilder, SlashCommandBuilder } from "discord.js";
import { mwRequireALToken } from "#middleware/alToken";
import { mwRequireAniListToken } from "#middleware/alToken";
import type { Command } from "#structures/index";

const name = "makeactivity";
Expand All @@ -11,7 +11,7 @@ export default {
name,
usage,
description,
middlewares: [mwRequireALToken],
middlewares: [mwRequireAniListToken],
commandType: "Anilist",
withBuilder: new SlashCommandBuilder()
.setName(name)
Expand Down Expand Up @@ -52,10 +52,10 @@ export default {
if (!interaction.isAutocomplete()) return;
try {
// Get the users media lists
const alUser = await getAnilistUser(interaction.user.id);
if (!alUser) return interaction.respond([{ name: "No Anilist account linked", value: "NaN" }]);
const aniListUser = await getAniListUser(interaction.user.id);
if (!aniListUser) return interaction.respond([{ name: "No Anilist account linked", value: "NaN" }]);

const vars = { userId: +alUser.anilistId };
const vars = { userId: +aniListUser.aniListId };
const response = (await graphQLRequest("ListQuery", vars)).data;
if (!response.User || !response.User.mediaListOptions) return interaction.respond([{ name: "No lists found for linked account", value: "NaN" }]);

Expand Down Expand Up @@ -93,12 +93,12 @@ export default {
const statusData = hookData?.subcommandType === "status" ? hookData : undefined;
const statusText = statusData?.text ?? interaction.options.getString("text", true);
const vars = { text: getEmojis(statusText), asHtml: true };
if (!interaction.ALtoken) throw new YuukoError("No Anilist token found.", { ephemeral: true });
if (!interaction.aniListToken) throw new YuukoError("No Anilist token found.", { ephemeral: true });

const {
data: { SaveTextActivity: data },
headers,
} = await graphQLRequest("SaveTextActivity", vars, interaction.ALtoken);
} = await graphQLRequest("SaveTextActivity", vars, interaction.aniListToken);
const userName = data?.user?.name || "Unknown";
const userText = data?.text || "Unknown";
if (!userName || !userText) return;
Expand Down Expand Up @@ -126,12 +126,12 @@ export default {
}
}

if (!interaction.ALtoken) throw new YuukoError("No Anilist token found.", { ephemeral: true });
if (!interaction.aniListToken) throw new YuukoError("No Anilist token found.", { ephemeral: true });

const {
data: { SaveMediaListEntry: data },
headers,
} = await graphQLRequest("SaveMediaList", vars, interaction.ALtoken);
} = await graphQLRequest("SaveMediaList", vars, interaction.aniListToken);
if (!data) throw new YuukoError("Something went wrong while making the activity.", { ephemeral: true });
const mediaListActivity = new EmbedBuilder()
.setURL(`https://anilist.co/${data?.media?.type || ""}/${data?.mediaId || ""}`)
Expand Down
8 changes: 4 additions & 4 deletions src/commands/manga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,22 @@ export default {
const cacheData = await redis.json.get(`_manga-${vars.mID}`) as MangaQuery["Media"] | null;

if (cacheData) {
if (interaction.alID) {
const _mediaListEntry = await redis.json.get(`_user${interaction.alID}-MANGA`) as Record<number, CacheEntry>;
if (interaction.aniListId) {
const _mediaListEntry = await redis.json.get(`_user${interaction.aniListId}-MANGA`) as Record<number, CacheEntry>;
if (!vars.mID) throw new YuukoError("No mID found in cache data.", { vars });
const mediaListEntry = _mediaListEntry ? _mediaListEntry[vars.mID] : null;
if (mediaListEntry) cacheData.mediaListEntry = mediaListEntry;
}

client.logger.debug("User cache hit", { seriesId: vars.mID, anilistId: interaction.alID, type: "generic" })
client.logger.debug("User cache hit", { seriesId: vars.mID, aniListId: interaction.aniListId, type: "generic" })

return void handleData({ media: cacheData }, interaction, client, "MANGA");
}

const {
data: { Media: data },
headers,
} = await graphQLRequest("Manga", vars, interaction.ALtoken);
} = await graphQLRequest("Manga", vars, interaction.aniListToken);

if (!data) {
throw new YuukoError("Couldn't find any data.", { vars });
Expand Down
Loading
Loading