diff --git a/slowcord/README.md b/src-slowcord/README.md
index 892b5763..892b5763 100644
--- a/slowcord/README.md
+++ b/src-slowcord/README.md
diff --git a/slowcord/bot/.vscode/launch.json b/src-slowcord/bot/.vscode/launch.json
index 92765e22..92765e22 100644
--- a/slowcord/bot/.vscode/launch.json
+++ b/src-slowcord/bot/.vscode/launch.json
diff --git a/slowcord/bot/.vscode/tasks.json b/src-slowcord/bot/.vscode/tasks.json
index 356126d8..356126d8 100644
--- a/slowcord/bot/.vscode/tasks.json
+++ b/src-slowcord/bot/.vscode/tasks.json
diff --git a/slowcord/bot/package-lock.json b/src-slowcord/bot/package-lock.json
index 0d72daab..0d72daab 100644
--- a/slowcord/bot/package-lock.json
+++ b/src-slowcord/bot/package-lock.json
diff --git a/slowcord/bot/package.json b/src-slowcord/bot/package.json
index 847cef09..847cef09 100644
--- a/slowcord/bot/package.json
+++ b/src-slowcord/bot/package.json
diff --git a/slowcord/bot/src/Bot.ts b/src-slowcord/bot/src/Bot.ts
index 45938846..45938846 100644
--- a/slowcord/bot/src/Bot.ts
+++ b/src-slowcord/bot/src/Bot.ts
diff --git a/slowcord/bot/src/commands/index.ts b/src-slowcord/bot/src/commands/index.ts
index d3b39e0f..d3b39e0f 100644
--- a/slowcord/bot/src/commands/index.ts
+++ b/src-slowcord/bot/src/commands/index.ts
diff --git a/slowcord/bot/src/commands/instance.ts b/src-slowcord/bot/src/commands/instance.ts
index ac0c9b2d..ac0c9b2d 100644
--- a/slowcord/bot/src/commands/instance.ts
+++ b/src-slowcord/bot/src/commands/instance.ts
diff --git a/slowcord/bot/src/index.ts b/src-slowcord/bot/src/index.ts
index ae69111b..ae69111b 100644
--- a/slowcord/bot/src/index.ts
+++ b/src-slowcord/bot/src/index.ts
diff --git a/slowcord/bot/tsconfig.json b/src-slowcord/bot/tsconfig.json
index 05bfc5c7..05bfc5c7 100644
--- a/slowcord/bot/tsconfig.json
+++ b/src-slowcord/bot/tsconfig.json
diff --git a/slowcord/login/.env.template b/src-slowcord/login/.env.template
index 34f6abeb..34f6abeb 100644
--- a/slowcord/login/.env.template
+++ b/src-slowcord/login/.env.template
diff --git a/slowcord/login/package-lock.json b/src-slowcord/login/package-lock.json
index 82eac102..82eac102 100644
--- a/slowcord/login/package-lock.json
+++ b/src-slowcord/login/package-lock.json
diff --git a/slowcord/login/package.json b/src-slowcord/login/package.json
index b458a875..b458a875 100644
--- a/slowcord/login/package.json
+++ b/src-slowcord/login/package.json
diff --git a/slowcord/login/public/css/index.css b/src-slowcord/login/public/css/index.css
index d4f5a4b4..d4f5a4b4 100644
--- a/slowcord/login/public/css/index.css
+++ b/src-slowcord/login/public/css/index.css
diff --git a/slowcord/login/public/js/handler.js b/src-slowcord/login/public/js/handler.js
index 68a656b4..68a656b4 100644
--- a/slowcord/login/public/js/handler.js
+++ b/src-slowcord/login/public/js/handler.js
diff --git a/slowcord/login/public/login.html b/src-slowcord/login/public/login.html
index 8cecd20b..8cecd20b 100644
--- a/slowcord/login/public/login.html
+++ b/src-slowcord/login/public/login.html
diff --git a/slowcord/login/public/register.html b/src-slowcord/login/public/register.html
index 40eecdbe..40eecdbe 100644
--- a/slowcord/login/public/register.html
+++ b/src-slowcord/login/public/register.html
diff --git a/slowcord/login/src/index.ts b/src-slowcord/login/src/index.ts
index a17e9eaa..a17e9eaa 100644
--- a/slowcord/login/src/index.ts
+++ b/src-slowcord/login/src/index.ts
diff --git a/slowcord/login/tsconfig.json b/src-slowcord/login/tsconfig.json
index b8a5965d..b8a5965d 100644
--- a/slowcord/login/tsconfig.json
+++ b/src-slowcord/login/tsconfig.json
diff --git a/slowcord/nginx/fosscord b/src-slowcord/nginx/fosscord
index f1d53de1..f1d53de1 100644
--- a/slowcord/nginx/fosscord
+++ b/src-slowcord/nginx/fosscord
diff --git a/slowcord/nginx/voice b/src-slowcord/nginx/voice
index b2b18c40..b2b18c40 100644
--- a/slowcord/nginx/voice
+++ b/src-slowcord/nginx/voice
diff --git a/slowcord/rules.md b/src-slowcord/rules.md
index ffae0846..ffae0846 100644
--- a/slowcord/rules.md
+++ b/src-slowcord/rules.md
diff --git a/slowcord/status/.env.template b/src-slowcord/status/.env.template
index e15dc56a..e15dc56a 100644
--- a/slowcord/status/.env.template
+++ b/src-slowcord/status/.env.template
diff --git a/slowcord/status/package-lock.json b/src-slowcord/status/package-lock.json
index a4f449ab..a4f449ab 100644
--- a/slowcord/status/package-lock.json
+++ b/src-slowcord/status/package-lock.json
diff --git a/slowcord/status/package.json b/src-slowcord/status/package.json
index ccec4f55..ccec4f55 100644
--- a/slowcord/status/package.json
+++ b/src-slowcord/status/package.json
diff --git a/slowcord/status/src/gateway.ts b/src-slowcord/status/src/gateway.ts
index 14944d09..14944d09 100644
--- a/slowcord/status/src/gateway.ts
+++ b/src-slowcord/status/src/gateway.ts
diff --git a/slowcord/status/src/index.ts b/src-slowcord/status/src/index.ts
index 735b8a9b..735b8a9b 100644
--- a/slowcord/status/src/index.ts
+++ b/src-slowcord/status/src/index.ts
diff --git a/slowcord/status/tsconfig.json b/src-slowcord/status/tsconfig.json
index 6d6ec56d..6d6ec56d 100644
--- a/slowcord/status/tsconfig.json
+++ b/src-slowcord/status/tsconfig.json
diff --git a/api/src/Server.ts b/src/api/Server.ts
index 4cf0917d..4cf0917d 100644
--- a/api/src/Server.ts
+++ b/src/api/Server.ts
diff --git a/src/api/global.d.ts b/src/api/global.d.ts
new file mode 100644
index 00000000..ed23cacb
--- /dev/null
+++ b/src/api/global.d.ts
@@ -0,0 +1,8 @@
+// declare global {
+// namespace Express {
+// interface Request {
+// user_id: any;
+// token: any;
+// }
+// }
+// }
diff --git a/api/src/index.ts b/src/api/index.ts
index 09663452..09663452 100644
--- a/api/src/index.ts
+++ b/src/api/index.ts
diff --git a/api/src/middlewares/Authentication.ts b/src/api/middlewares/Authentication.ts
index 1df7911b..1df7911b 100644
--- a/api/src/middlewares/Authentication.ts
+++ b/src/api/middlewares/Authentication.ts
diff --git a/api/src/middlewares/BodyParser.ts b/src/api/middlewares/BodyParser.ts
index 4cb376bc..4cb376bc 100644
--- a/api/src/middlewares/BodyParser.ts
+++ b/src/api/middlewares/BodyParser.ts
diff --git a/api/src/middlewares/CORS.ts b/src/api/middlewares/CORS.ts
index 20260cf9..20260cf9 100644
--- a/api/src/middlewares/CORS.ts
+++ b/src/api/middlewares/CORS.ts
diff --git a/api/src/middlewares/ErrorHandler.ts b/src/api/middlewares/ErrorHandler.ts
index 2012b91c..2012b91c 100644
--- a/api/src/middlewares/ErrorHandler.ts
+++ b/src/api/middlewares/ErrorHandler.ts
diff --git a/api/src/middlewares/RateLimit.ts b/src/api/middlewares/RateLimit.ts
index 57645c0b..57645c0b 100644
--- a/api/src/middlewares/RateLimit.ts
+++ b/src/api/middlewares/RateLimit.ts
diff --git a/api/src/middlewares/Translation.ts b/src/api/middlewares/Translation.ts
index baabf221..741d6baf 100644
--- a/api/src/middlewares/Translation.ts
+++ b/src/api/middlewares/Translation.ts
@@ -6,8 +6,8 @@ import i18nextBackend from "i18next-node-fs-backend";
import { Router } from "express";
export async function initTranslation(router: Router) {
- const languages = fs.readdirSync(path.join(__dirname, "..", "..", "locales"));
- const namespaces = fs.readdirSync(path.join(__dirname, "..", "..", "locales", "en"));
+ const languages = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "locales"));
+ const namespaces = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "locales", "en"));
const ns = namespaces.filter((x) => x.endsWith(".json")).map((x) => x.slice(0, x.length - 5));
await i18next
diff --git a/api/src/middlewares/index.ts b/src/api/middlewares/index.ts
index f0c50dbe..f0c50dbe 100644
--- a/api/src/middlewares/index.ts
+++ b/src/api/middlewares/index.ts
diff --git a/api/src/routes/-/healthz.ts b/src/api/routes/-/healthz.ts
index f7bcfebf..d9d1c026 100644
--- a/api/src/routes/-/healthz.ts
+++ b/src/api/routes/-/healthz.ts
@@ -1,17 +1,13 @@
import { Router, Response, Request } from "express";
import { route } from "@fosscord/api";
-import { getConnection } from "typeorm";
+import { getDatabase } from "@fosscord/util";
const router = Router();
router.get("/", route({}), (req: Request, res: Response) => {
- try {
- // test that the database is alive & responding
- getConnection();
- return res.sendStatus(200);
- } catch (e) {
- res.sendStatus(503);
- }
+ if (!getDatabase()) return res.sendStatus(503);
+
+ return res.sendStatus(200);
});
export default router;
diff --git a/api/src/routes/-/monitorz.ts b/src/api/routes/-/monitorz.ts
index f85cd099..f85cd099 100644
--- a/api/src/routes/-/monitorz.ts
+++ b/src/api/routes/-/monitorz.ts
diff --git a/api/src/routes/-/readyz.ts b/src/api/routes/-/readyz.ts
index f7bcfebf..d9d1c026 100644
--- a/api/src/routes/-/readyz.ts
+++ b/src/api/routes/-/readyz.ts
@@ -1,17 +1,13 @@
import { Router, Response, Request } from "express";
import { route } from "@fosscord/api";
-import { getConnection } from "typeorm";
+import { getDatabase } from "@fosscord/util";
const router = Router();
router.get("/", route({}), (req: Request, res: Response) => {
- try {
- // test that the database is alive & responding
- getConnection();
- return res.sendStatus(200);
- } catch (e) {
- res.sendStatus(503);
- }
+ if (!getDatabase()) return res.sendStatus(503);
+
+ return res.sendStatus(200);
});
export default router;
diff --git a/api/src/routes/applications/#id/entitlements.ts b/src/api/routes/applications/#id/entitlements.ts
index cfcfe40f..cfcfe40f 100644
--- a/api/src/routes/applications/#id/entitlements.ts
+++ b/src/api/routes/applications/#id/entitlements.ts
diff --git a/api/src/routes/applications/detectable.ts b/src/api/routes/applications/detectable.ts
index 28ce42da..28ce42da 100644
--- a/api/src/routes/applications/detectable.ts
+++ b/src/api/routes/applications/detectable.ts
diff --git a/api/src/routes/applications/index.ts b/src/api/routes/applications/index.ts
index 28ce42da..28ce42da 100644
--- a/api/src/routes/applications/index.ts
+++ b/src/api/routes/applications/index.ts
diff --git a/api/src/routes/auth/location-metadata.ts b/src/api/routes/auth/location-metadata.ts
index f4c2bd16..f4c2bd16 100644
--- a/api/src/routes/auth/location-metadata.ts
+++ b/src/api/routes/auth/location-metadata.ts
diff --git a/api/src/routes/auth/login.ts b/src/api/routes/auth/login.ts
index bcaccb30..bcaccb30 100644
--- a/api/src/routes/auth/login.ts
+++ b/src/api/routes/auth/login.ts
diff --git a/api/src/routes/auth/mfa/totp.ts b/src/api/routes/auth/mfa/totp.ts
index cec6e5ee..50b9e9c8 100644
--- a/api/src/routes/auth/mfa/totp.ts
+++ b/src/api/routes/auth/mfa/totp.ts
@@ -26,7 +26,14 @@ router.post("/", route({ body: "TotpSchema" }), async (req: Request, res: Respon
],
});
- const backup = await BackupCode.findOne({ code: code, expired: false, consumed: false, user: { id: user.id }});
+ const backup = await BackupCode.findOne({
+ where: {
+ code: code,
+ expired: false,
+ consumed: false,
+ user: { id: user.id }
+ }
+ });
if (!backup) {
const ret = verifyToken(user.totp_secret!, code);
diff --git a/api/src/routes/auth/register.ts b/src/api/routes/auth/register.ts
index f74d0d63..b7122dad 100644
--- a/api/src/routes/auth/register.ts
+++ b/src/api/routes/auth/register.ts
@@ -117,7 +117,7 @@ router.post("/", route({ body: "RegisterSchema" }), async (req: Request, res: Re
}
// check if there is already an account with this email
- const exists = await User.findOne({ email: email });
+ const exists = await User.findOne({ where: { email: email } });
if (exists) {
throw FieldErrors({
diff --git a/api/src/routes/auth/verify/view-backup-codes-challenge.ts b/src/api/routes/auth/verify/view-backup-codes-challenge.ts
index be651686..36bfeb0c 100644
--- a/api/src/routes/auth/verify/view-backup-codes-challenge.ts
+++ b/src/api/routes/auth/verify/view-backup-codes-challenge.ts
@@ -11,7 +11,7 @@ export interface BackupCodesChallengeSchema {
router.post("/", route({ body: "BackupCodesChallengeSchema" }), async (req: Request, res: Response) => {
const { password } = req.body as BackupCodesChallengeSchema;
- const user = await User.findOneOrFail({ id: req.user_id }, { select: ["data"] });
+ const user = await User.findOneOrFail({ where: { id: req.user_id }, select: ["data"] });
if (!await bcrypt.compare(password, user.data.hash || "")) {
throw FieldErrors({ password: { message: req.t("auth:login.INVALID_PASSWORD"), code: "INVALID_PASSWORD" } });
@@ -20,7 +20,7 @@ router.post("/", route({ body: "BackupCodesChallengeSchema" }), async (req: Requ
return res.json({
nonce: "NoncePlaceholder",
regenerate_nonce: "RegenNoncePlaceholder",
- })
+ });
});
export default router;
diff --git a/api/src/routes/channels/#channel_id/followers.ts b/src/api/routes/channels/#channel_id/followers.ts
index 641af4f8..641af4f8 100644
--- a/api/src/routes/channels/#channel_id/followers.ts
+++ b/src/api/routes/channels/#channel_id/followers.ts
diff --git a/api/src/routes/channels/#channel_id/index.ts b/src/api/routes/channels/#channel_id/index.ts
index 932a933a..0340a616 100644
--- a/api/src/routes/channels/#channel_id/index.ts
+++ b/src/api/routes/channels/#channel_id/index.ts
@@ -18,7 +18,7 @@ const router: Router = Router();
router.get("/", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res: Response) => {
const { channel_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
return res.send(channel);
});
@@ -81,7 +81,7 @@ router.patch("/", route({ body: "ChannelModifySchema", permission: "MANAGE_CHANN
const { channel_id } = req.params;
if (payload.icon) payload.icon = await handleFile(`/channel-icons/${channel_id}`, payload.icon);
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
channel.assign(payload);
await Promise.all([
diff --git a/api/src/routes/channels/#channel_id/invites.ts b/src/api/routes/channels/#channel_id/invites.ts
index 9c361164..fd8339ad 100644
--- a/api/src/routes/channels/#channel_id/invites.ts
+++ b/src/api/routes/channels/#channel_id/invites.ts
@@ -20,44 +20,44 @@ export interface InviteCreateSchema {
}
router.post("/", route({ body: "InviteCreateSchema", permission: "CREATE_INSTANT_INVITE", right: "CREATE_INVITES" }),
- async (req: Request, res: Response) => {
- const { user_id } = req;
- const { channel_id } = req.params;
- const channel = await Channel.findOneOrFail({ where: { id: channel_id }, select: ["id", "name", "type", "guild_id"] });
- isTextChannel(channel.type);
+ async (req: Request, res: Response) => {
+ const { user_id } = req;
+ const { channel_id } = req.params;
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id }, select: ["id", "name", "type", "guild_id"] });
+ isTextChannel(channel.type);
- if (!channel.guild_id) {
- throw new HTTPError("This channel doesn't exist", 404);
- }
- const { guild_id } = channel;
+ if (!channel.guild_id) {
+ throw new HTTPError("This channel doesn't exist", 404);
+ }
+ const { guild_id } = channel;
- const expires_at = new Date(req.body.max_age * 1000 + Date.now());
+ const expires_at = new Date(req.body.max_age * 1000 + Date.now());
- const invite = await new Invite({
- code: random(),
- temporary: req.body.temporary,
- uses: 0,
- max_uses: req.body.max_uses,
- max_age: req.body.max_age,
- expires_at,
- created_at: new Date(),
- guild_id,
- channel_id: channel_id,
- inviter_id: user_id
- }).save();
- const data = invite.toJSON();
- data.inviter = await User.getPublicUser(req.user_id);
- data.guild = await Guild.findOne({ id: guild_id });
- data.channel = channel;
+ const invite = await Invite.create({
+ code: random(),
+ temporary: req.body.temporary,
+ uses: 0,
+ max_uses: req.body.max_uses,
+ max_age: req.body.max_age,
+ expires_at,
+ created_at: new Date(),
+ guild_id,
+ channel_id: channel_id,
+ inviter_id: user_id
+ }).save();
+ const data = invite.toJSON();
+ data.inviter = await User.getPublicUser(req.user_id);
+ data.guild = await Guild.findOne({ where: { id: guild_id } });
+ data.channel = channel;
- await emitEvent({ event: "INVITE_CREATE", data, guild_id } as InviteCreateEvent);
- res.status(201).send(data);
-});
+ await emitEvent({ event: "INVITE_CREATE", data, guild_id } as InviteCreateEvent);
+ res.status(201).send(data);
+ });
router.get("/", route({ permission: "MANAGE_CHANNELS" }), async (req: Request, res: Response) => {
const { user_id } = req;
const { channel_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
if (!channel.guild_id) {
throw new HTTPError("This channel doesn't exist", 404);
diff --git a/api/src/routes/channels/#channel_id/messages/#message_id/ack.ts b/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts
index 1e3564d8..3abae7ce 100644
--- a/api/src/routes/channels/#channel_id/messages/#message_id/ack.ts
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts
@@ -19,8 +19,8 @@ router.post("/", route({ body: "MessageAcknowledgeSchema" }), async (req: Reques
const permission = await getPermission(req.user_id, undefined, channel_id);
permission.hasThrow("VIEW_CHANNEL");
- let read_state = await ReadState.findOne({ user_id: req.user_id, channel_id });
- if (!read_state) read_state = new ReadState({ user_id: req.user_id, channel_id });
+ let read_state = await ReadState.findOne({ where: { user_id: req.user_id, channel_id } });
+ if (!read_state) read_state = ReadState.create({ user_id: req.user_id, channel_id });
read_state.last_message_id = message_id;
await read_state.save();
diff --git a/api/src/routes/channels/#channel_id/messages/#message_id/crosspost.ts b/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts
index b2cb6763..b2cb6763 100644
--- a/api/src/routes/channels/#channel_id/messages/#message_id/crosspost.ts
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts
diff --git a/api/src/routes/channels/#channel_id/messages/#message_id/index.ts b/src/api/routes/channels/#channel_id/messages/#message_id/index.ts
index 37734397..a02a9abe 100644
--- a/api/src/routes/channels/#channel_id/messages/#message_id/index.ts
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/index.ts
@@ -7,12 +7,12 @@ import {
FosscordApiErrors,
getPermission,
getRights,
- Message,
+ Message,
MessageCreateEvent,
MessageDeleteEvent,
MessageUpdateEvent,
Snowflake,
- uploadFile
+ uploadFile
} from "@fosscord/util";
import { Router, Response, Request } from "express";
import multer from "multer";
@@ -40,14 +40,14 @@ router.patch("/", route({ body: "MessageCreateSchema", permission: "SEND_MESSAGE
const message = await Message.findOneOrFail({ where: { id: message_id, channel_id }, relations: ["attachments"] });
const permissions = await getPermission(req.user_id, undefined, channel_id);
-
+
const rights = await getRights(req.user_id);
if ((req.user_id !== message.author_id)) {
if (!rights.has("MANAGE_MESSAGES")) {
permissions.hasThrow("MANAGE_MESSAGES");
body = { flags: body.flags };
-// guild admins can only suppress embeds of other messages, no such restriction imposed to instance-wide admins
+ // guild admins can only suppress embeds of other messages, no such restriction imposed to instance-wide admins
}
} else rights.hasThrow("SELF_EDIT_MESSAGES");
@@ -94,7 +94,7 @@ router.put(
const { channel_id, message_id } = req.params;
var body = req.body as MessageCreateSchema;
const attachments: Attachment[] = [];
-
+
const rights = await getRights(req.user_id);
rights.hasThrow("SEND_MESSAGES");
@@ -103,13 +103,13 @@ router.put(
throw new HTTPError("Message IDs must be positive integers", 400);
}
- const snowflake = Snowflake.deconstruct(message_id)
+ const snowflake = Snowflake.deconstruct(message_id);
if (Date.now() < snowflake.timestamp) {
// message is in the future
throw FosscordApiErrors.CANNOT_BACKFILL_TO_THE_FUTURE;
}
- const exists = await Message.findOne({ where: { id: message_id, channel_id: channel_id }});
+ const exists = await Message.findOne({ where: { id: message_id, channel_id: channel_id } });
if (exists) {
throw FosscordApiErrors.CANNOT_REPLACE_BY_BACKFILL;
}
@@ -117,7 +117,7 @@ router.put(
if (req.file) {
try {
const file = await uploadFile(`/attachments/${req.params.channel_id}`, req.file);
- attachments.push({ ...file, proxy_url: file.url });
+ attachments.push(Attachment.create({ ...file, proxy_url: file.url }));
} catch (error) {
return res.status(400).json(error);
}
@@ -135,13 +135,13 @@ router.put(
embeds,
channel_id,
attachments,
- edited_timestamp: null,
+ edited_timestamp: undefined,
timestamp: new Date(snowflake.timestamp),
});
//Fix for the client bug
- delete message.member
-
+ delete message.member;
+
await Promise.all([
message.save(),
emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent),
@@ -160,7 +160,7 @@ router.get("/", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res:
const message = await Message.findOneOrFail({ where: { id: message_id, channel_id }, relations: ["attachments"] });
const permissions = await getPermission(req.user_id, undefined, channel_id);
-
+
if (message.author_id !== req.user_id) permissions.hasThrow("READ_MESSAGE_HISTORY");
return res.json(message);
@@ -169,9 +169,9 @@ router.get("/", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res:
router.delete("/", route({}), async (req: Request, res: Response) => {
const { message_id, channel_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
- const message = await Message.findOneOrFail({ id: message_id });
-
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+ const message = await Message.findOneOrFail({ where: { id: message_id } });
+
const rights = await getRights(req.user_id);
if ((message.author_id !== req.user_id)) {
diff --git a/api/src/routes/channels/#channel_id/messages/#message_id/reactions.ts b/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts
index d93cf70f..c3cca05d 100644
--- a/api/src/routes/channels/#channel_id/messages/#message_id/reactions.ts
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts
@@ -39,7 +39,7 @@ function getEmoji(emoji: string): PartialEmoji {
router.delete("/", route({ permission: "MANAGE_MESSAGES" }), async (req: Request, res: Response) => {
const { message_id, channel_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
await Message.update({ id: message_id, channel_id }, { reactions: [] });
@@ -60,7 +60,7 @@ router.delete("/:emoji", route({ permission: "MANAGE_MESSAGES" }), async (req: R
const { message_id, channel_id } = req.params;
const emoji = getEmoji(req.params.emoji);
- const message = await Message.findOneOrFail({ id: message_id, channel_id });
+ const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
if (!already_added) throw new HTTPError("Reaction not found", 404);
@@ -87,7 +87,7 @@ router.get("/:emoji", route({ permission: "VIEW_CHANNEL" }), async (req: Request
const { message_id, channel_id } = req.params;
const emoji = getEmoji(req.params.emoji);
- const message = await Message.findOneOrFail({ id: message_id, channel_id });
+ const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
const reaction = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
if (!reaction) throw new HTTPError("Reaction not found", 404);
@@ -106,14 +106,14 @@ router.put("/:emoji/:user_id", route({ permission: "READ_MESSAGE_HISTORY", right
if (user_id !== "@me") throw new HTTPError("Invalid user");
const emoji = getEmoji(req.params.emoji);
- const channel = await Channel.findOneOrFail({ id: channel_id });
- const message = await Message.findOneOrFail({ id: message_id, channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+ const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
if (!already_added) req.permission!.hasThrow("ADD_REACTIONS");
if (emoji.id) {
- const external_emoji = await Emoji.findOneOrFail({ id: emoji.id });
+ const external_emoji = await Emoji.findOneOrFail({ where: { id: emoji.id } });
if (!already_added) req.permission!.hasThrow("USE_EXTERNAL_EMOJIS");
emoji.animated = external_emoji.animated;
emoji.name = external_emoji.name;
@@ -126,7 +126,7 @@ router.put("/:emoji/:user_id", route({ permission: "READ_MESSAGE_HISTORY", right
await message.save();
- const member = channel.guild_id && (await Member.findOneOrFail({ id: req.user_id }));
+ const member = channel.guild_id && (await Member.findOneOrFail({ where: { id: req.user_id } }));
await emitEvent({
event: "MESSAGE_REACTION_ADD",
@@ -149,8 +149,8 @@ router.delete("/:emoji/:user_id", route({}), async (req: Request, res: Response)
const emoji = getEmoji(req.params.emoji);
- const channel = await Channel.findOneOrFail({ id: channel_id });
- const message = await Message.findOneOrFail({ id: message_id, channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+ const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
if (user_id === "@me") user_id = req.user_id;
else {
diff --git a/api/src/routes/channels/#channel_id/messages/bulk-delete.ts b/src/api/routes/channels/#channel_id/messages/bulk-delete.ts
index 6eacf249..b6fd37f4 100644
--- a/api/src/routes/channels/#channel_id/messages/bulk-delete.ts
+++ b/src/api/routes/channels/#channel_id/messages/bulk-delete.ts
@@ -17,7 +17,7 @@ export interface BulkDeleteSchema {
// https://discord.com/developers/docs/resources/channel#bulk-delete-messages
router.post("/", route({ body: "BulkDeleteSchema" }), async (req: Request, res: Response) => {
const { channel_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
if (!channel.guild_id) throw new HTTPError("Can't bulk delete dm channel messages", 400);
const rights = await getRights(req.user_id);
@@ -35,7 +35,7 @@ router.post("/", route({ body: "BulkDeleteSchema" }), async (req: Request, res:
if (messages.length > maxBulkDelete) throw new HTTPError(`You cannot delete more than ${maxBulkDelete} messages`);
}
- await Message.delete(messages.map((x) => ({ id: x })));
+ await Message.delete(messages);
await emitEvent({
event: "MESSAGE_DELETE_BULK",
diff --git a/api/src/routes/channels/#channel_id/messages/index.ts b/src/api/routes/channels/#channel_id/messages/index.ts
index 3c014f5c..154dc8ed 100644
--- a/api/src/routes/channels/#channel_id/messages/index.ts
+++ b/src/api/routes/channels/#channel_id/messages/index.ts
@@ -203,7 +203,7 @@ router.post(
for (var currFile of files) {
try {
const file = await uploadFile(`/attachments/${channel.id}`, currFile);
- attachments.push({ ...file, proxy_url: file.url });
+ attachments.push(Attachment.create({ ...file, proxy_url: file.url }));
}
catch (error) {
return res.status(400).json(error);
@@ -220,7 +220,7 @@ router.post(
embeds,
channel_id,
attachments,
- edited_timestamp: null,
+ edited_timestamp: undefined,
timestamp: new Date()
});
diff --git a/api/src/routes/channels/#channel_id/permissions.ts b/src/api/routes/channels/#channel_id/permissions.ts
index 2eded853..e74a0255 100644
--- a/api/src/routes/channels/#channel_id/permissions.ts
+++ b/src/api/routes/channels/#channel_id/permissions.ts
@@ -16,7 +16,7 @@ const router: Router = Router();
// TODO: Only permissions your bot has in the guild or channel can be allowed/denied (unless your bot has a MANAGE_ROLES overwrite in the channel)
-export interface ChannelPermissionOverwriteSchema extends ChannelPermissionOverwrite {}
+export interface ChannelPermissionOverwriteSchema extends ChannelPermissionOverwrite { }
router.put(
"/:overwrite_id",
@@ -25,13 +25,13 @@ router.put(
const { channel_id, overwrite_id } = req.params;
const body = req.body as ChannelPermissionOverwriteSchema;
- var channel = await Channel.findOneOrFail({ id: channel_id });
+ var channel = await Channel.findOneOrFail({ where: { id: channel_id } });
if (!channel.guild_id) throw new HTTPError("Channel not found", 404);
if (body.type === 0) {
- if (!(await Role.count({ id: overwrite_id }))) throw new HTTPError("role not found", 404);
+ if (!(await Role.count({ where: { id: overwrite_id } }))) throw new HTTPError("role not found", 404);
} else if (body.type === 1) {
- if (!(await Member.count({ id: overwrite_id }))) throw new HTTPError("user not found", 404);
+ if (!(await Member.count({ where: { id: overwrite_id } }))) throw new HTTPError("user not found", 404);
} else throw new HTTPError("type not supported", 501);
// @ts-ignore
@@ -64,7 +64,7 @@ router.put(
router.delete("/:overwrite_id", route({ permission: "MANAGE_ROLES" }), async (req: Request, res: Response) => {
const { channel_id, overwrite_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
if (!channel.guild_id) throw new HTTPError("Channel not found", 404);
channel.permission_overwrites = channel.permission_overwrites!.filter((x) => x.id === overwrite_id);
diff --git a/api/src/routes/channels/#channel_id/pins.ts b/src/api/routes/channels/#channel_id/pins.ts
index e71e659f..30507c71 100644
--- a/api/src/routes/channels/#channel_id/pins.ts
+++ b/src/api/routes/channels/#channel_id/pins.ts
@@ -17,12 +17,12 @@ const router: Router = Router();
router.put("/:message_id", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res: Response) => {
const { channel_id, message_id } = req.params;
- const message = await Message.findOneOrFail({ id: message_id });
+ const message = await Message.findOneOrFail({ where: { id: message_id } });
// * in dm channels anyone can pin messages -> only check for guilds
if (message.guild_id) req.permission!.hasThrow("MANAGE_MESSAGES");
- const pinned_count = await Message.count({ channel: { id: channel_id }, pinned: true });
+ const pinned_count = await Message.count({ where: { channel: { id: channel_id }, pinned: true } });
const { maxPins } = Config.get().limits.channel;
if (pinned_count >= maxPins) throw DiscordApiErrors.MAXIMUM_PINS.withParams(maxPins);
@@ -50,10 +50,10 @@ router.put("/:message_id", route({ permission: "VIEW_CHANNEL" }), async (req: Re
router.delete("/:message_id", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res: Response) => {
const { channel_id, message_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
if (channel.guild_id) req.permission!.hasThrow("MANAGE_MESSAGES");
- const message = await Message.findOneOrFail({ id: message_id });
+ const message = await Message.findOneOrFail({ where: { id: message_id } });
message.pinned = false;
await Promise.all([
@@ -82,7 +82,7 @@ router.delete("/:message_id", route({ permission: "VIEW_CHANNEL" }), async (req:
router.get("/", route({ permission: ["READ_MESSAGE_HISTORY"] }), async (req: Request, res: Response) => {
const { channel_id } = req.params;
- let pins = await Message.find({ channel_id: channel_id, pinned: true });
+ let pins = await Message.find({ where: { channel_id: channel_id, pinned: true } });
res.send(pins);
});
diff --git a/api/src/routes/channels/#channel_id/purge.ts b/src/api/routes/channels/#channel_id/purge.ts
index 28b52b50..bfac27ee 100644
--- a/api/src/routes/channels/#channel_id/purge.ts
+++ b/src/api/routes/channels/#channel_id/purge.ts
@@ -12,10 +12,10 @@ import {
FosscordApiErrors,
getPermission,
getRights,
- Message,
+ Message,
MessageDeleteBulkEvent,
Snowflake,
- uploadFile
+ uploadFile
} from "@fosscord/util";
import { Router, Response, Request } from "express";
import multer from "multer";
@@ -27,7 +27,7 @@ export default router;
export interface PurgeSchema {
before: string;
- after: string
+ after: string;
}
/**
@@ -35,8 +35,8 @@ TODO: apply the delete bit by bit to prevent client and database stress
**/
router.post("/", route({ /*body: "PurgeSchema",*/ }), async (req: Request, res: Response) => {
const { channel_id } = req.params;
- const channel = await Channel.findOneOrFail({ id: channel_id });
-
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+
if (!channel.guild_id) throw new HTTPError("Can't purge dm channels", 400);
isTextChannel(channel.type);
@@ -46,7 +46,7 @@ router.post("/", route({ /*body: "PurgeSchema",*/ }), async (req: Request, res:
permissions.hasThrow("MANAGE_MESSAGES");
permissions.hasThrow("MANAGE_CHANNELS");
}
-
+
const { before, after } = req.body as PurgeSchema;
// TODO: send the deletion event bite-by-bite to prevent client stress
@@ -55,25 +55,25 @@ router.post("/", route({ /*body: "PurgeSchema",*/ }), async (req: Request, res:
order: { id: "ASC" },
// take: limit,
where: {
- channel_id,
- id: Between(after, before), // the right way around
- author_id: rights.has("SELF_DELETE_MESSAGES") ? undefined : Not(req.user_id)
- // if you lack the right of self-deletion, you can't delete your own messages, even in purges
- },
+ channel_id,
+ id: Between(after, before), // the right way around
+ author_id: rights.has("SELF_DELETE_MESSAGES") ? undefined : Not(req.user_id)
+ // if you lack the right of self-deletion, you can't delete your own messages, even in purges
+ },
relations: ["author", "webhook", "application", "mentions", "mention_roles", "mention_channels", "sticker_items", "attachments"]
};
-
+
const messages = await Message.find(query);
const endpoint = Config.get().cdn.endpointPublic;
-
- if (messages.length == 0) {
+
+ if (messages.length == 0) {
res.sendStatus(304);
return;
}
- await Message.delete(messages.map((x) => ({ id: x })));
-
+ await Message.delete(messages.map((x) => x.id));
+
await emitEvent({
event: "MESSAGE_DELETE_BULK",
channel_id,
diff --git a/api/src/routes/channels/#channel_id/recipients.ts b/src/api/routes/channels/#channel_id/recipients.ts
index e6466211..25854415 100644
--- a/api/src/routes/channels/#channel_id/recipients.ts
+++ b/src/api/routes/channels/#channel_id/recipients.ts
@@ -28,7 +28,7 @@ router.put("/:user_id", route({}), async (req: Request, res: Response) => {
throw DiscordApiErrors.INVALID_RECIPIENT; //TODO is this the right error?
}
- channel.recipients!.push(new Recipient({ channel_id: channel_id, user_id: user_id }));
+ channel.recipients!.push(Recipient.create({ channel_id: channel_id, user_id: user_id }));
await channel.save();
await emitEvent({
diff --git a/api/src/routes/channels/#channel_id/typing.ts b/src/api/routes/channels/#channel_id/typing.ts
index 56652368..99460f6e 100644
--- a/api/src/routes/channels/#channel_id/typing.ts
+++ b/src/api/routes/channels/#channel_id/typing.ts
@@ -8,7 +8,7 @@ router.post("/", route({ permission: "SEND_MESSAGES" }), async (req: Request, re
const { channel_id } = req.params;
const user_id = req.user_id;
const timestamp = Date.now();
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
const member = await Member.findOne({ where: { id: user_id, guild_id: channel.guild_id }, relations: ["roles", "user"] });
await emitEvent({
diff --git a/api/src/routes/channels/#channel_id/webhooks.ts b/src/api/routes/channels/#channel_id/webhooks.ts
index 92895da6..93f70a41 100644
--- a/api/src/routes/channels/#channel_id/webhooks.ts
+++ b/src/api/routes/channels/#channel_id/webhooks.ts
@@ -22,12 +22,12 @@ router.get("/", route({}), async (req: Request, res: Response) => {
// TODO: use Image Data Type for avatar instead of String
router.post("/", route({ body: "WebhookCreateSchema", permission: "MANAGE_WEBHOOKS" }), async (req: Request, res: Response) => {
const channel_id = req.params.channel_id;
- const channel = await Channel.findOneOrFail({ id: channel_id });
+ const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
isTextChannel(channel.type);
if (!channel.guild_id) throw new HTTPError("Not a guild channel", 400);
- const webhook_count = await Webhook.count({ channel_id });
+ const webhook_count = await Webhook.count({ where: { channel_id } });
const { maxWebhooks } = Config.get().limits.channel;
if (webhook_count > maxWebhooks) throw DiscordApiErrors.MAXIMUM_WEBHOOKS.withParams(maxWebhooks);
diff --git a/api/src/routes/discoverable-guilds.ts b/src/api/routes/discoverable-guilds.ts
index 0aa2baa9..383e2b24 100644
--- a/api/src/routes/discoverable-guilds.ts
+++ b/src/api/routes/discoverable-guilds.ts
@@ -2,6 +2,7 @@ import { Guild, Config } from "@fosscord/util";
import { Router, Request, Response } from "express";
import { route } from "@fosscord/api";
+import { Like } from "typeorm";
const router = Router();
@@ -16,14 +17,14 @@ router.get("/", route({}), async (req: Request, res: Response) => {
if (categories == undefined) {
guilds = showAllGuilds
? await Guild.find({ take: Math.abs(Number(limit || configLimit)) })
- : await Guild.find({ where: `"features" LIKE '%DISCOVERABLE%'`, take: Math.abs(Number(limit || configLimit)) });
+ : await Guild.find({ where: { features: Like(`%DISCOVERABLE%`) }, take: Math.abs(Number(limit || configLimit)) });
} else {
guilds = showAllGuilds
- ? await Guild.find({ where: `"primary_category_id" = ${categories}`, take: Math.abs(Number(limit || configLimit)) })
- : await Guild.find({
- where: `"primary_category_id" = ${categories} AND "features" LIKE '%DISCOVERABLE%'`,
- take: Math.abs(Number(limit || configLimit))
- });
+ ? await Guild.find({ where: { primary_category_id: categories.toString() }, take: Math.abs(Number(limit || configLimit)) })
+ : await Guild.find({
+ where: { primary_category_id: categories.toString(), features: Like("%DISCOVERABLE%") },
+ take: Math.abs(Number(limit || configLimit))
+ });
}
const total = guilds ? guilds.length : undefined;
diff --git a/api/src/routes/discovery.ts b/src/api/routes/discovery.ts
index 1991400e..6ab2cc13 100644
--- a/api/src/routes/discovery.ts
+++ b/src/api/routes/discovery.ts
@@ -10,7 +10,7 @@ router.get("/categories", route({}), async (req: Request, res: Response) => {
const { locale, primary_only } = req.query;
- const out = primary_only ? await Categories.find() : await Categories.find({ where: `"is_primary" = "true"` });
+ const out = primary_only ? await Categories.find() : await Categories.find({ where: { is_primary: true } });
res.send(out);
});
diff --git a/api/src/routes/downloads.ts b/src/api/routes/downloads.ts
index ddfc080c..df3df911 100644
--- a/api/src/routes/downloads.ts
+++ b/src/api/routes/downloads.ts
@@ -10,9 +10,9 @@ router.get("/:branch", route({}), async (req: Request, res: Response) => {
const { platform } = req.query;
//TODO
- if(!platform || !["linux", "osx", "win"].includes(platform.toString())) return res.status(404)
+ if (!platform || !["linux", "osx", "win"].includes(platform.toString())) return res.status(404);
- const release = await Release.findOneOrFail({ name: client.releases.upstreamVersion });
+ const release = await Release.findOneOrFail({ where: { name: client.releases.upstreamVersion } });
res.redirect(release[`win_url`]);
});
diff --git a/api/src/routes/experiments.ts b/src/api/routes/experiments.ts
index 7be86fb8..7be86fb8 100644
--- a/api/src/routes/experiments.ts
+++ b/src/api/routes/experiments.ts
diff --git a/api/src/routes/gateway/bot.ts b/src/api/routes/gateway/bot.ts
index f1dbb9df..f1dbb9df 100644
--- a/api/src/routes/gateway/bot.ts
+++ b/src/api/routes/gateway/bot.ts
diff --git a/api/src/routes/gateway/index.ts b/src/api/routes/gateway/index.ts
index 9bad7478..9bad7478 100644
--- a/api/src/routes/gateway/index.ts
+++ b/src/api/routes/gateway/index.ts
diff --git a/api/src/routes/gifs/search.ts b/src/api/routes/gifs/search.ts
index 9ad7a592..c7468641 100644
--- a/api/src/routes/gifs/search.ts
+++ b/src/api/routes/gifs/search.ts
@@ -20,7 +20,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
headers: { "Content-Type": "application/json" }
});
- const { results } = await response.json();
+ const { results } = await response.json() as any; // TODO: types
res.json(results.map(parseGifResult)).status(200);
});
diff --git a/api/src/routes/gifs/trending-gifs.ts b/src/api/routes/gifs/trending-gifs.ts
index 6d97bf7c..52a8969d 100644
--- a/api/src/routes/gifs/trending-gifs.ts
+++ b/src/api/routes/gifs/trending-gifs.ts
@@ -20,7 +20,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
headers: { "Content-Type": "application/json" }
});
- const { results } = await response.json();
+ const { results } = await response.json() as any; // TODO: types
res.json(results.map(parseGifResult)).status(200);
});
diff --git a/api/src/routes/gifs/trending.ts b/src/api/routes/gifs/trending.ts
index c81b4c08..aa976c3f 100644
--- a/api/src/routes/gifs/trending.ts
+++ b/src/api/routes/gifs/trending.ts
@@ -50,8 +50,8 @@ router.get("/", route({}), async (req: Request, res: Response) => {
})
]);
- const { tags } = await responseSource.json();
- const { results } = await trendGifSource.json();
+ const { tags } = await responseSource.json() as any; // TODO: types
+ const { results } = await trendGifSource.json() as any; //TODO: types;
res.json({
categories: tags.map((x: any) => ({ name: x.searchterm, src: x.image })),
diff --git a/api/src/routes/guild-recommendations.ts b/src/api/routes/guild-recommendations.ts
index 1432f39c..b851d710 100644
--- a/api/src/routes/guild-recommendations.ts
+++ b/src/api/routes/guild-recommendations.ts
@@ -2,6 +2,7 @@ import { Guild, Config } from "@fosscord/util";
import { Router, Request, Response } from "express";
import { route } from "@fosscord/api";
+import { Like } from "typeorm";
const router = Router();
@@ -16,8 +17,8 @@ router.get("/", route({}), async (req: Request, res: Response) => {
const guilds = showAllGuilds
? await Guild.find({ take: Math.abs(Number(limit || 24)) })
- : await Guild.find({ where: `"features" LIKE '%DISCOVERABLE%'`, take: Math.abs(Number(limit || 24)) });
- res.send({ recommended_guilds: guilds, load_id: `server_recs/${genLoadId(32)}`}).status(200);
+ : await Guild.find({ where: { features: Like("%DISCOVERABLE%") }, take: Math.abs(Number(limit || 24)) });
+ res.send({ recommended_guilds: guilds, load_id: `server_recs/${genLoadId(32)}` }).status(200);
});
export default router;
diff --git a/api/src/routes/guilds/#guild_id/audit-logs.ts b/src/api/routes/guilds/#guild_id/audit-logs.ts
index a4f2f800..a4f2f800 100644
--- a/api/src/routes/guilds/#guild_id/audit-logs.ts
+++ b/src/api/routes/guilds/#guild_id/audit-logs.ts
diff --git a/api/src/routes/guilds/#guild_id/bans.ts b/src/api/routes/guilds/#guild_id/bans.ts
index 1ce41936..51d3ca67 100644
--- a/api/src/routes/guilds/#guild_id/bans.ts
+++ b/src/api/routes/guilds/#guild_id/bans.ts
@@ -1,5 +1,5 @@
import { Request, Response, Router } from "express";
-import { DiscordApiErrors, emitEvent, getPermission, GuildBanAddEvent, GuildBanRemoveEvent, Guild, Ban, User, Member } from "@fosscord/util";
+import { DiscordApiErrors, emitEvent, GuildBanAddEvent, GuildBanRemoveEvent, Ban, User, Member } from "@fosscord/util";
import { HTTPError } from "lambert-server";
import { getIpAdress, route } from "@fosscord/api";
@@ -32,7 +32,7 @@ const router: Router = Router();
router.get("/", route({ permission: "BAN_MEMBERS" }), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- let bans = await Ban.find({ guild_id: guild_id });
+ let bans = await Ban.find({ where: { guild_id: guild_id } });
let promisesToAwait: object[] = [];
const bansObj: object[] = [];
@@ -65,16 +65,16 @@ router.get("/:user", route({ permission: "BAN_MEMBERS" }), async (req: Request,
const { guild_id } = req.params;
const user_id = req.params.ban;
- let ban = await Ban.findOneOrFail({ guild_id: guild_id, user_id: user_id }) as BanRegistrySchema;
-
+ let ban = await Ban.findOneOrFail({ where: { guild_id: guild_id, user_id: user_id } }) as BanRegistrySchema;
+
if (ban.user_id === ban.executor_id) throw DiscordApiErrors.UNKNOWN_BAN;
// pretend self-bans don't exist to prevent victim chasing
-
+
/* Filter secret from registry. */
-
+
ban = ban as BanModeratorSchema;
- delete ban.ip
+ delete ban.ip;
return res.json(ban);
});
@@ -83,14 +83,14 @@ router.put("/:user_id", route({ body: "BanCreateSchema", permission: "BAN_MEMBER
const { guild_id } = req.params;
const banned_user_id = req.params.user_id;
- if ( (req.user_id === banned_user_id) && (banned_user_id === req.permission!.cache.guild?.owner_id))
+ if ((req.user_id === banned_user_id) && (banned_user_id === req.permission!.cache.guild?.owner_id))
throw new HTTPError("You are the guild owner, hence can't ban yourself", 403);
-
+
if (req.permission!.cache.guild?.owner_id === banned_user_id) throw new HTTPError("You can't ban the owner", 400);
-
+
const banned_user = await User.getPublicUser(banned_user_id);
- const ban = new Ban({
+ const ban = Ban.create({
user_id: banned_user_id,
guild_id: guild_id,
ip: getIpAdress(req),
@@ -114,15 +114,15 @@ router.put("/:user_id", route({ body: "BanCreateSchema", permission: "BAN_MEMBER
return res.json(ban);
});
-router.put("/@me", route({ body: "BanCreateSchema"}), async (req: Request, res: Response) => {
+router.put("/@me", route({ body: "BanCreateSchema" }), async (req: Request, res: Response) => {
const { guild_id } = req.params;
const banned_user = await User.getPublicUser(req.params.user_id);
- if (req.permission!.cache.guild?.owner_id === req.params.user_id)
+ if (req.permission!.cache.guild?.owner_id === req.params.user_id)
throw new HTTPError("You are the guild owner, hence can't ban yourself", 403);
-
- const ban = new Ban({
+
+ const ban = Ban.create({
user_id: req.params.user_id,
guild_id: guild_id,
ip: getIpAdress(req),
@@ -149,13 +149,13 @@ router.put("/@me", route({ body: "BanCreateSchema"}), async (req: Request, res:
router.delete("/:user_id", route({ permission: "BAN_MEMBERS" }), async (req: Request, res: Response) => {
const { guild_id, user_id } = req.params;
- let ban = await Ban.findOneOrFail({ guild_id: guild_id, user_id: user_id });
-
+ let ban = await Ban.findOneOrFail({ where: { guild_id: guild_id, user_id: user_id } });
+
if (ban.user_id === ban.executor_id) throw DiscordApiErrors.UNKNOWN_BAN;
// make self-bans irreversible and hide them from view to avoid victim chasing
-
+
const banned_user = await User.getPublicUser(user_id);
-
+
await Promise.all([
Ban.delete({
user_id: user_id,
diff --git a/api/src/routes/guilds/#guild_id/channels.ts b/src/api/routes/guilds/#guild_id/channels.ts
index a921fa21..11f727fc 100644
--- a/api/src/routes/guilds/#guild_id/channels.ts
+++ b/src/api/routes/guilds/#guild_id/channels.ts
@@ -7,7 +7,7 @@ const router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- const channels = await Channel.find({ guild_id });
+ const channels = await Channel.find({ where: { guild_id } });
res.json(channels);
});
@@ -22,7 +22,7 @@ router.post("/", route({ body: "ChannelModifySchema", permission: "MANAGE_CHANNE
res.status(201).json(channel);
});
-export type ChannelReorderSchema = { id: string; position?: number; lock_permissions?: boolean; parent_id?: string }[];
+export type ChannelReorderSchema = { id: string; position?: number; lock_permissions?: boolean; parent_id?: string; }[];
router.patch("/", route({ body: "ChannelReorderSchema", permission: "MANAGE_CHANNELS" }), async (req: Request, res: Response) => {
// changes guild channel position
@@ -48,7 +48,7 @@ router.patch("/", route({ body: "ChannelReorderSchema", permission: "MANAGE_CHAN
}
await Channel.update({ guild_id, id: x.id }, opts);
- const channel = await Channel.findOneOrFail({ guild_id, id: x.id });
+ const channel = await Channel.findOneOrFail({ where: { guild_id, id: x.id } });
await emitEvent({ event: "CHANNEL_UPDATE", data: channel, channel_id: x.id, guild_id } as ChannelUpdateEvent);
})
diff --git a/api/src/routes/guilds/#guild_id/delete.ts b/src/api/routes/guilds/#guild_id/delete.ts
index bd158c56..bd158c56 100644
--- a/api/src/routes/guilds/#guild_id/delete.ts
+++ b/src/api/routes/guilds/#guild_id/delete.ts
diff --git a/api/src/routes/guilds/#guild_id/discovery-requirements.ts b/src/api/routes/guilds/#guild_id/discovery-requirements.ts
index ad20633f..ad20633f 100644
--- a/api/src/routes/guilds/#guild_id/discovery-requirements.ts
+++ b/src/api/routes/guilds/#guild_id/discovery-requirements.ts
diff --git a/api/src/routes/guilds/#guild_id/emojis.ts b/src/api/routes/guilds/#guild_id/emojis.ts
index 85d7ac05..75998e04 100644
--- a/api/src/routes/guilds/#guild_id/emojis.ts
+++ b/src/api/routes/guilds/#guild_id/emojis.ts
@@ -41,19 +41,20 @@ router.post("/", route({ body: "EmojiCreateSchema", permission: "MANAGE_EMOJIS_A
const body = req.body as EmojiCreateSchema;
const id = Snowflake.generate();
- const emoji_count = await Emoji.count({ guild_id: guild_id });
+ const emoji_count = await Emoji.count({ where: { guild_id: guild_id } });
const { maxEmojis } = Config.get().limits.guild;
if (emoji_count >= maxEmojis) throw DiscordApiErrors.MAXIMUM_NUMBER_OF_EMOJIS_REACHED.withParams(maxEmojis);
if (body.require_colons == null) body.require_colons = true;
- const user = await User.findOneOrFail({ id: req.user_id });
+ const user = await User.findOneOrFail({ where: { id: req.user_id } });
body.image = (await handleFile(`/emojis/${id}`, body.image)) as string;
- const emoji = await new Emoji({
+ const emoji = await Emoji.create({
id: id,
guild_id: guild_id,
...body,
+ require_colons: body.require_colons ?? undefined, // schema allows nulls, db does not
user: user,
managed: false,
animated: false, // TODO: Add support animated emojis
@@ -66,7 +67,7 @@ router.post("/", route({ body: "EmojiCreateSchema", permission: "MANAGE_EMOJIS_A
guild_id: guild_id,
data: {
guild_id: guild_id,
- emojis: await Emoji.find({ guild_id: guild_id })
+ emojis: await Emoji.find({ where: { guild_id: guild_id } })
}
} as GuildEmojisUpdateEvent);
@@ -80,14 +81,14 @@ router.patch(
const { emoji_id, guild_id } = req.params;
const body = req.body as EmojiModifySchema;
- const emoji = await new Emoji({ ...body, id: emoji_id, guild_id: guild_id }).save();
+ const emoji = await Emoji.create({ ...body, id: emoji_id, guild_id: guild_id }).save();
await emitEvent({
event: "GUILD_EMOJIS_UPDATE",
guild_id: guild_id,
data: {
guild_id: guild_id,
- emojis: await Emoji.find({ guild_id: guild_id })
+ emojis: await Emoji.find({ where: { guild_id: guild_id } })
}
} as GuildEmojisUpdateEvent);
@@ -108,7 +109,7 @@ router.delete("/:emoji_id", route({ permission: "MANAGE_EMOJIS_AND_STICKERS" }),
guild_id: guild_id,
data: {
guild_id: guild_id,
- emojis: await Emoji.find({ guild_id: guild_id })
+ emojis: await Emoji.find({ where: { guild_id: guild_id } })
}
} as GuildEmojisUpdateEvent);
diff --git a/api/src/routes/guilds/#guild_id/index.ts b/src/api/routes/guilds/#guild_id/index.ts
index 45e30a74..45bbe348 100644
--- a/api/src/routes/guilds/#guild_id/index.ts
+++ b/src/api/routes/guilds/#guild_id/index.ts
@@ -27,8 +27,8 @@ router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
const [guild, member] = await Promise.all([
- Guild.findOneOrFail({ id: guild_id }),
- Member.findOne({ guild_id: guild_id, id: req.user_id })
+ Guild.findOneOrFail({ where: { id: guild_id } }),
+ Member.findOne({ where: { guild_id: guild_id, id: req.user_id } })
]);
if (!member) throw new HTTPError("You are not a member of the guild you are trying to access", 401);
@@ -38,17 +38,17 @@ router.get("/", route({}), async (req: Request, res: Response) => {
return res.send(guild);
});
-router.patch("/", route({ body: "GuildUpdateSchema"}), async (req: Request, res: Response) => {
+router.patch("/", route({ body: "GuildUpdateSchema" }), async (req: Request, res: Response) => {
const body = req.body as GuildUpdateSchema;
const { guild_id } = req.params;
-
-
+
+
const rights = await getRights(req.user_id);
const permission = await getPermission(req.user_id, guild_id);
-
- if (!rights.has("MANAGE_GUILDS")||!permission.has("MANAGE_GUILD"))
+
+ if (!rights.has("MANAGE_GUILDS") || !permission.has("MANAGE_GUILD"))
throw DiscordApiErrors.MISSING_PERMISSIONS.withParams("MANAGE_GUILD");
-
+
// TODO: guild update check image
if (body.icon) body.icon = await handleFile(`/icons/${guild_id}`, body.icon);
diff --git a/api/src/routes/guilds/#guild_id/integrations.ts b/src/api/routes/guilds/#guild_id/integrations.ts
index abf997c9..abf997c9 100644
--- a/api/src/routes/guilds/#guild_id/integrations.ts
+++ b/src/api/routes/guilds/#guild_id/integrations.ts
diff --git a/api/src/routes/guilds/#guild_id/invites.ts b/src/api/routes/guilds/#guild_id/invites.ts
index b7534e31..b7534e31 100644
--- a/api/src/routes/guilds/#guild_id/invites.ts
+++ b/src/api/routes/guilds/#guild_id/invites.ts
diff --git a/api/src/routes/guilds/#guild_id/member-verification.ts b/src/api/routes/guilds/#guild_id/member-verification.ts
index 265a1b35..265a1b35 100644
--- a/api/src/routes/guilds/#guild_id/member-verification.ts
+++ b/src/api/routes/guilds/#guild_id/member-verification.ts
diff --git a/api/src/routes/guilds/#guild_id/members/#member_id/index.ts b/src/api/routes/guilds/#guild_id/members/#member_id/index.ts
index d923c10f..d785eb00 100644
--- a/api/src/routes/guilds/#guild_id/members/#member_id/index.ts
+++ b/src/api/routes/guilds/#guild_id/members/#member_id/index.ts
@@ -14,7 +14,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id, member_id } = req.params;
await Member.IsInGuildOrFail(req.user_id, guild_id);
- const member = await Member.findOneOrFail({ id: member_id, guild_id });
+ const member = await Member.findOneOrFail({ where: { id: member_id, guild_id } });
return res.json(member);
});
@@ -26,13 +26,13 @@ router.patch("/", route({ body: "MemberChangeSchema" }), async (req: Request, re
const member = await Member.findOneOrFail({ where: { id: member_id, guild_id }, relations: ["roles", "user"] });
const permission = await getPermission(req.user_id, guild_id);
- const everyone = await Role.findOneOrFail({ guild_id: guild_id, name: "@everyone", position: 0 });
+ const everyone = await Role.findOneOrFail({ where: { guild_id: guild_id, name: "@everyone", position: 0 } });
if (body.roles) {
permission.hasThrow("MANAGE_ROLES");
if (body.roles.indexOf(everyone.id) === -1) body.roles.push(everyone.id);
- member.roles = body.roles.map((x) => new Role({ id: x })); // foreign key constraint will fail if role doesn't exist
+ member.roles = body.roles.map((x) => Role.create({ id: x })); // foreign key constraint will fail if role doesn't exist
}
if ('nick' in body) {
diff --git a/api/src/routes/guilds/#guild_id/members/#member_id/nick.ts b/src/api/routes/guilds/#guild_id/members/#member_id/nick.ts
index 27f7f65d..27f7f65d 100644
--- a/api/src/routes/guilds/#guild_id/members/#member_id/nick.ts
+++ b/src/api/routes/guilds/#guild_id/members/#member_id/nick.ts
diff --git a/api/src/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts b/src/api/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts
index 8f5ca7ba..8f5ca7ba 100644
--- a/api/src/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts
+++ b/src/api/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts
diff --git a/api/src/routes/guilds/#guild_id/members/index.ts b/src/api/routes/guilds/#guild_id/members/index.ts
index b730a4e7..b730a4e7 100644
--- a/api/src/routes/guilds/#guild_id/members/index.ts
+++ b/src/api/routes/guilds/#guild_id/members/index.ts
diff --git a/api/src/routes/guilds/#guild_id/messages/search.ts b/src/api/routes/guilds/#guild_id/messages/search.ts
index a7516ebd..a7516ebd 100644
--- a/api/src/routes/guilds/#guild_id/messages/search.ts
+++ b/src/api/routes/guilds/#guild_id/messages/search.ts
diff --git a/api/src/routes/guilds/#guild_id/premium.ts b/src/api/routes/guilds/#guild_id/premium.ts
index 75361ac6..75361ac6 100644
--- a/api/src/routes/guilds/#guild_id/premium.ts
+++ b/src/api/routes/guilds/#guild_id/premium.ts
diff --git a/api/src/routes/guilds/#guild_id/prune.ts b/src/api/routes/guilds/#guild_id/prune.ts
index 0e587d22..cf3466f1 100644
--- a/api/src/routes/guilds/#guild_id/prune.ts
+++ b/src/api/routes/guilds/#guild_id/prune.ts
@@ -33,7 +33,7 @@ export const inactiveMembers = async (guild_id: string, user_id: string, days: n
//I'm sure I can do this in the above db query ( and it would probably be better to do so ), but oh well.
if (roles.length && members.length) members = members.filter((user) => user.roles?.some((role) => roles.includes(role.id)));
- const me = await Member.findOneOrFail({ id: user_id, guild_id }, { relations: ["roles"] });
+ const me = await Member.findOneOrFail({ where: { id: user_id, guild_id }, relations: ["roles"] });
const myHighestRole = Math.max(...(me.roles?.map((x) => x.position) || []));
const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
diff --git a/api/src/routes/guilds/#guild_id/regions.ts b/src/api/routes/guilds/#guild_id/regions.ts
index 75d24fd1..308d5ee5 100644
--- a/api/src/routes/guilds/#guild_id/regions.ts
+++ b/src/api/routes/guilds/#guild_id/regions.ts
@@ -7,7 +7,7 @@ const router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
//TODO we should use an enum for guild's features and not hardcoded strings
return res.json(await getVoiceRegions(getIpAdress(req), guild.features.includes("VIP_REGIONS")));
});
diff --git a/api/src/routes/guilds/#guild_id/roles/#role_id/index.ts b/src/api/routes/guilds/#guild_id/roles/#role_id/index.ts
index 16b5a59f..a01068c0 100644
--- a/api/src/routes/guilds/#guild_id/roles/#role_id/index.ts
+++ b/src/api/routes/guilds/#guild_id/roles/#role_id/index.ts
@@ -9,7 +9,7 @@ const router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id, role_id } = req.params;
await Member.IsInGuildOrFail(req.user_id, guild_id);
- const role = await Role.findOneOrFail({ guild_id, id: role_id });
+ const role = await Role.findOneOrFail({ where: { guild_id, id: role_id } });
return res.json(role);
});
@@ -44,7 +44,7 @@ router.patch("/", route({ body: "RoleModifySchema", permission: "MANAGE_ROLES" }
if (body.icon && body.icon.length) body.icon = await handleFile(`/role-icons/${role_id}`, body.icon as string);
else body.icon = undefined;
- const role = new Role({
+ const role = Role.create({
...body,
id: role_id,
guild_id,
diff --git a/api/src/routes/guilds/#guild_id/roles/index.ts b/src/api/routes/guilds/#guild_id/roles/index.ts
index 53465105..7e839f08 100644
--- a/api/src/routes/guilds/#guild_id/roles/index.ts
+++ b/src/api/routes/guilds/#guild_id/roles/index.ts
@@ -37,7 +37,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
await Member.IsInGuildOrFail(req.user_id, guild_id);
- const roles = await Role.find({ guild_id: guild_id });
+ const roles = await Role.find({ where: { guild_id: guild_id } });
return res.json(roles);
});
@@ -46,12 +46,12 @@ router.post("/", route({ body: "RoleModifySchema", permission: "MANAGE_ROLES" })
const guild_id = req.params.guild_id;
const body = req.body as RoleModifySchema;
- const role_count = await Role.count({ guild_id });
+ const role_count = await Role.count({ where: { guild_id } });
const { maxRoles } = Config.get().limits.guild;
if (role_count > maxRoles) throw DiscordApiErrors.MAXIMUM_ROLES.withParams(maxRoles);
- const role = new Role({
+ const role = Role.create({
// values before ...body are default and can be overriden
position: 0,
hoist: false,
@@ -62,8 +62,8 @@ router.post("/", route({ body: "RoleModifySchema", permission: "MANAGE_ROLES" })
managed: false,
permissions: String(req.permission!.bitfield & BigInt(body.permissions || "0")),
tags: undefined,
- icon: null,
- unicode_emoji: null
+ icon: undefined,
+ unicode_emoji: undefined
});
await Promise.all([
diff --git a/api/src/routes/guilds/#guild_id/stickers.ts b/src/api/routes/guilds/#guild_id/stickers.ts
index 4ea1dce1..7a4e71ee 100644
--- a/api/src/routes/guilds/#guild_id/stickers.ts
+++ b/src/api/routes/guilds/#guild_id/stickers.ts
@@ -19,7 +19,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
await Member.IsInGuildOrFail(req.user_id, guild_id);
- res.json(await Sticker.find({ guild_id }));
+ res.json(await Sticker.find({ where: { guild_id } }));
});
const bodyParser = multer({
@@ -43,7 +43,7 @@ router.post(
const id = Snowflake.generate();
const [sticker] = await Promise.all([
- new Sticker({
+ Sticker.create({
...body,
guild_id,
id,
@@ -79,7 +79,7 @@ router.get("/:sticker_id", route({}), async (req: Request, res: Response) => {
const { guild_id, sticker_id } = req.params;
await Member.IsInGuildOrFail(req.user_id, guild_id);
- res.json(await Sticker.findOneOrFail({ guild_id, id: sticker_id }));
+ res.json(await Sticker.findOneOrFail({ where: { guild_id, id: sticker_id } }));
});
export interface ModifyGuildStickerSchema {
@@ -105,7 +105,7 @@ router.patch(
const { guild_id, sticker_id } = req.params;
const body = req.body as ModifyGuildStickerSchema;
- const sticker = await new Sticker({ ...body, guild_id, id: sticker_id }).save();
+ const sticker = await Sticker.create({ ...body, guild_id, id: sticker_id }).save();
await sendStickerUpdateEvent(guild_id);
return res.json(sticker);
@@ -118,7 +118,7 @@ async function sendStickerUpdateEvent(guild_id: string) {
guild_id: guild_id,
data: {
guild_id: guild_id,
- stickers: await Sticker.find({ guild_id: guild_id })
+ stickers: await Sticker.find({ where: { guild_id: guild_id } })
}
} as GuildStickersUpdateEvent);
}
diff --git a/api/src/routes/guilds/#guild_id/templates.ts b/src/api/routes/guilds/#guild_id/templates.ts
index 5179e761..0444c402 100644
--- a/api/src/routes/guilds/#guild_id/templates.ts
+++ b/src/api/routes/guilds/#guild_id/templates.ts
@@ -36,7 +36,7 @@ export interface TemplateModifySchema {
router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- var templates = await Template.find({ source_guild_id: guild_id });
+ var templates = await Template.find({ where: { source_guild_id: guild_id } });
return res.json(templates);
});
@@ -44,10 +44,10 @@ router.get("/", route({}), async (req: Request, res: Response) => {
router.post("/", route({ body: "TemplateCreateSchema", permission: "MANAGE_GUILD" }), async (req: Request, res: Response) => {
const { guild_id } = req.params;
const guild = await Guild.findOneOrFail({ where: { id: guild_id }, select: TemplateGuildProjection });
- const exists = await Template.findOneOrFail({ id: guild_id }).catch((e) => {});
+ const exists = await Template.findOneOrFail({ where: { id: guild_id } }).catch((e) => { });
if (exists) throw new HTTPError("Template already exists", 400);
- const template = await new Template({
+ const template = await Template.create({
...req.body,
code: generateCode(),
creator_id: req.user_id,
@@ -75,7 +75,7 @@ router.put("/:code", route({ permission: "MANAGE_GUILD" }), async (req: Request,
const { code, guild_id } = req.params;
const guild = await Guild.findOneOrFail({ where: { id: guild_id }, select: TemplateGuildProjection });
- const template = await new Template({ code, serialized_source_guild: guild }).save();
+ const template = await Template.create({ code, serialized_source_guild: guild }).save();
res.json(template);
});
@@ -84,7 +84,7 @@ router.patch("/:code", route({ body: "TemplateModifySchema", permission: "MANAGE
const { code, guild_id } = req.params;
const { name, description } = req.body;
- const template = await new Template({ code, name: name, description: description, source_guild_id: guild_id }).save();
+ const template = await Template.create({ code, name: name, description: description, source_guild_id: guild_id }).save();
res.json(template);
});
diff --git a/api/src/routes/guilds/#guild_id/vanity-url.ts b/src/api/routes/guilds/#guild_id/vanity-url.ts
index 29cd25e2..040bc1fd 100644
--- a/api/src/routes/guilds/#guild_id/vanity-url.ts
+++ b/src/api/routes/guilds/#guild_id/vanity-url.ts
@@ -9,7 +9,7 @@ const InviteRegex = /\W/g;
router.get("/", route({ permission: "MANAGE_GUILD" }), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
if (!guild.features.includes("ALIASABLE_NAMES")) {
const invite = await Invite.findOne({ where: { guild_id: guild_id, vanity_url: true } });
@@ -37,17 +37,17 @@ router.patch("/", route({ body: "VanityUrlSchema", permission: "MANAGE_GUILD" })
const body = req.body as VanityUrlSchema;
const code = body.code?.replace(InviteRegex, "");
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
if (!guild.features.includes("VANITY_URL")) throw new HTTPError("Your guild doesn't support vanity urls");
if (!code || code.length === 0) throw new HTTPError("Code cannot be null or empty");
- const invite = await Invite.findOne({ code });
+ const invite = await Invite.findOne({ where: { code } });
if (invite) throw new HTTPError("Invite already exists");
- const { id } = await Channel.findOneOrFail({ guild_id, type: ChannelType.GUILD_TEXT });
+ const { id } = await Channel.findOneOrFail({ where: { guild_id, type: ChannelType.GUILD_TEXT } });
- await new Invite({
+ await Invite.create({
vanity_url: true,
code: code,
temporary: false,
diff --git a/api/src/routes/guilds/#guild_id/voice-states/#user_id/index.ts b/src/api/routes/guilds/#guild_id/voice-states/#user_id/index.ts
index f9fbea54..b7fdfecd 100644
--- a/api/src/routes/guilds/#guild_id/voice-states/#user_id/index.ts
+++ b/src/api/routes/guilds/#guild_id/voice-states/#user_id/index.ts
@@ -34,14 +34,16 @@ router.patch("/", route({ body: "VoiceStateUpdateSchema" }), async (req: Request
if (body.request_to_speak_timestamp) perms.hasThrow("REQUEST_TO_SPEAK");
const voice_state = await VoiceState.findOne({
- guild_id,
- channel_id: body.channel_id,
- user_id
+ where: {
+ guild_id,
+ channel_id: body.channel_id,
+ user_id
+ }
});
if (!voice_state) throw DiscordApiErrors.UNKNOWN_VOICE_STATE;
voice_state.assign(body);
- const channel = await Channel.findOneOrFail({ guild_id, id: body.channel_id });
+ const channel = await Channel.findOneOrFail({ where: { guild_id, id: body.channel_id } });
if (channel.type !== ChannelType.GUILD_STAGE_VOICE) {
throw DiscordApiErrors.CANNOT_EXECUTE_ON_THIS_CHANNEL_TYPE;
}
diff --git a/api/src/routes/guilds/#guild_id/webhooks.ts b/src/api/routes/guilds/#guild_id/webhooks.ts
index 8b2febea..8b2febea 100644
--- a/api/src/routes/guilds/#guild_id/webhooks.ts
+++ b/src/api/routes/guilds/#guild_id/webhooks.ts
diff --git a/api/src/routes/guilds/#guild_id/welcome-screen.ts b/src/api/routes/guilds/#guild_id/welcome-screen.ts
index 5c7a9daa..a57255f0 100644
--- a/api/src/routes/guilds/#guild_id/welcome-screen.ts
+++ b/src/api/routes/guilds/#guild_id/welcome-screen.ts
@@ -19,7 +19,7 @@ export interface GuildUpdateWelcomeScreenSchema {
router.get("/", route({}), async (req: Request, res: Response) => {
const guild_id = req.params.guild_id;
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
await Member.IsInGuildOrFail(req.user_id, guild_id);
res.json(guild.welcome_screen);
@@ -29,7 +29,7 @@ router.patch("/", route({ body: "GuildUpdateWelcomeScreenSchema", permission: "M
const guild_id = req.params.guild_id;
const body = req.body as GuildUpdateWelcomeScreenSchema;
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
if (!guild.welcome_screen.enabled) throw new HTTPError("Welcome screen disabled", 400);
if (body.welcome_channels) guild.welcome_screen.welcome_channels = body.welcome_channels; // TODO: check if they exist and are valid
diff --git a/api/src/routes/guilds/#guild_id/widget.json.ts b/src/api/routes/guilds/#guild_id/widget.json.ts
index c31519fa..be5bf23f 100644
--- a/api/src/routes/guilds/#guild_id/widget.json.ts
+++ b/src/api/routes/guilds/#guild_id/widget.json.ts
@@ -17,18 +17,19 @@ const router: Router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
if (!guild.widget_enabled) throw new HTTPError("Widget Disabled", 404);
// Fetch existing widget invite for widget channel
- var invite = await Invite.findOne({ channel_id: guild.widget_channel_id });
+ var invite = await Invite.findOne({ where: { channel_id: guild.widget_channel_id } });
if (guild.widget_channel_id && !invite) {
// Create invite for channel if none exists
// TODO: Refactor invite create code to a shared function
const max_age = 86400; // 24 hours
const expires_at = new Date(max_age * 1000 + Date.now());
- const body = {
+
+ invite = await Invite.create({
code: random(),
temporary: false,
uses: 0,
@@ -38,10 +39,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
created_at: new Date(),
guild_id,
channel_id: guild.widget_channel_id,
- inviter_id: null
- };
-
- invite = await new Invite(body).save();
+ }).save();
}
// Fetch voice channels, and the @everyone permissions object
@@ -63,7 +61,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
// Fetch members
// TODO: Understand how Discord's max 100 random member sample works, and apply to here (see top of this file)
- let members = await Member.find({ guild_id: guild_id });
+ let members = await Member.find({ where: { guild_id: guild_id } });
// Construct object to respond with
const data = {
diff --git a/api/src/routes/guilds/#guild_id/widget.png.ts b/src/api/routes/guilds/#guild_id/widget.png.ts
index 4c82b740..721b59fb 100644
--- a/api/src/routes/guilds/#guild_id/widget.png.ts
+++ b/src/api/routes/guilds/#guild_id/widget.png.ts
@@ -14,7 +14,7 @@ const router: Router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
if (!guild.widget_enabled) throw new HTTPError("Unknown Guild", 404);
// Fetch guild information
diff --git a/api/src/routes/guilds/#guild_id/widget.ts b/src/api/routes/guilds/#guild_id/widget.ts
index 2640618d..103f84a3 100644
--- a/api/src/routes/guilds/#guild_id/widget.ts
+++ b/src/api/routes/guilds/#guild_id/widget.ts
@@ -13,7 +13,7 @@ const router: Router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- const guild = await Guild.findOneOrFail({ id: guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
return res.json({ enabled: guild.widget_enabled || false, channel_id: guild.widget_channel_id || null });
});
diff --git a/api/src/routes/guilds/index.ts b/src/api/routes/guilds/index.ts
index 489dea49..d44cd735 100644
--- a/api/src/routes/guilds/index.ts
+++ b/src/api/routes/guilds/index.ts
@@ -24,9 +24,9 @@ router.post("/", route({ body: "GuildCreateSchema", right: "CREATE_GUILDS" }), a
const body = req.body as GuildCreateSchema;
const { maxGuilds } = Config.get().limits.user;
- const guild_count = await Member.count({ id: req.user_id });
+ const guild_count = await Member.count({ where: { id: req.user_id } });
const rights = await getRights(req.user_id);
- if ((guild_count >= maxGuilds)&&!rights.has("MANAGE_GUILDS")) {
+ if ((guild_count >= maxGuilds) && !rights.has("MANAGE_GUILDS")) {
throw DiscordApiErrors.MAXIMUM_GUILDS.withParams(maxGuilds);
}
diff --git a/api/src/routes/guilds/templates/index.ts b/src/api/routes/guilds/templates/index.ts
index 3d922e85..e281214f 100644
--- a/api/src/routes/guilds/templates/index.ts
+++ b/src/api/routes/guilds/templates/index.ts
@@ -15,9 +15,9 @@ router.get("/:code", route({}), async (req: Request, res: Response) => {
if (!enabled) res.json({ code: 403, message: "Template creation & usage is disabled on this instance." }).sendStatus(403);
const { code } = req.params;
-
+
if (code.startsWith("discord:")) {
- if (!allowDiscordTemplates) return res.json({ code: 403, message: "Discord templates cannot be used on this instance." }).sendStatus(403);
+ if (!allowDiscordTemplates) return res.json({ code: 403, message: "Discord templates cannot be used on this instance." }).sendStatus(403);
const discordTemplateID = code.split("discord:", 2)[1];
const discordTemplateData = await fetch(`https://discord.com/api/v9/guilds/templates/${discordTemplateID}`, {
@@ -28,12 +28,12 @@ router.get("/:code", route({}), async (req: Request, res: Response) => {
}
if (code.startsWith("external:")) {
- if (!allowRaws) return res.json({ code: 403, message: "Importing raws is disabled on this instance." }).sendStatus(403);
+ if (!allowRaws) return res.json({ code: 403, message: "Importing raws is disabled on this instance." }).sendStatus(403);
return res.json(code.split("external:", 2)[1]);
}
- const template = await Template.findOneOrFail({ code: code });
+ const template = await Template.findOneOrFail({ where: { code: code } });
res.json(template);
});
@@ -47,23 +47,23 @@ router.post("/:code", route({ body: "GuildTemplateCreateSchema" }), async (req:
const { maxGuilds } = Config.get().limits.user;
- const guild_count = await Member.count({ id: req.user_id });
+ const guild_count = await Member.count({ where: { id: req.user_id } });
if (guild_count >= maxGuilds) {
throw DiscordApiErrors.MAXIMUM_GUILDS.withParams(maxGuilds);
}
- const template = await Template.findOneOrFail({ code: code });
+ const template = await Template.findOneOrFail({ where: { code: code } });
const guild_id = Snowflake.generate();
const [guild, role] = await Promise.all([
- new Guild({
+ Guild.create({
...body,
...template.serialized_source_guild,
id: guild_id,
owner_id: req.user_id
}).save(),
- new Role({
+ Role.create({
id: guild_id,
guild_id: guild_id,
color: 0,
@@ -71,9 +71,8 @@ router.post("/:code", route({ body: "GuildTemplateCreateSchema" }), async (req:
managed: true,
mentionable: true,
name: "@everyone",
- permissions: BigInt("2251804225"),
+ permissions: BigInt("2251804225").toString(), // TODO: where did this come from?
position: 0,
- tags: null
}).save()
]);
diff --git a/api/src/routes/invites/index.ts b/src/api/routes/invites/index.ts
index eeafb22a..c268085f 100644
--- a/api/src/routes/invites/index.ts
+++ b/src/api/routes/invites/index.ts
@@ -13,15 +13,15 @@ router.get("/:code", route({}), async (req: Request, res: Response) => {
res.status(200).send(invite);
});
-router.post("/:code", route({right: "USE_MASS_INVITES"}), async (req: Request, res: Response) => {
+router.post("/:code", route({ right: "USE_MASS_INVITES" }), async (req: Request, res: Response) => {
const { code } = req.params;
- const { guild_id } = await Invite.findOneOrFail({ code })
- const { features } = await Guild.findOneOrFail({ id: guild_id});
- const { public_flags } = await User.findOneOrFail({ id: req.user_id });
-
- if(features.includes("INTERNAL_EMPLOYEE_ONLY") && (public_flags & 1) !== 1) throw new HTTPError("Only intended for the staff of this server.", 401);
- if(features.includes("INVITES_CLOSED")) throw new HTTPError("Sorry, this guild has joins closed.", 403);
-
+ const { guild_id } = await Invite.findOneOrFail({ where: { code: code } });
+ const { features } = await Guild.findOneOrFail({ where: { id: guild_id } });
+ const { public_flags } = await User.findOneOrFail({ where: { id: req.user_id } });
+
+ if (features.includes("INTERNAL_EMPLOYEE_ONLY") && (public_flags & 1) !== 1) throw new HTTPError("Only intended for the staff of this server.", 401);
+ if (features.includes("INVITES_CLOSED")) throw new HTTPError("Sorry, this guild has joins closed.", 403);
+
const invite = await Invite.joinGuild(req.user_id, code);
res.json(invite);
@@ -30,7 +30,7 @@ router.post("/:code", route({right: "USE_MASS_INVITES"}), async (req: Request, r
// * cant use permission of route() function because path doesn't have guild_id/channel_id
router.delete("/:code", route({}), async (req: Request, res: Response) => {
const { code } = req.params;
- const invite = await Invite.findOneOrFail({ code });
+ const invite = await Invite.findOneOrFail({ where: { code } });
const { guild_id, channel_id } = invite;
const permission = await getPermission(req.user_id, guild_id, channel_id);
diff --git a/api/src/routes/oauth2/tokens.ts b/src/api/routes/oauth2/tokens.ts
index bd284221..bd284221 100644
--- a/api/src/routes/oauth2/tokens.ts
+++ b/src/api/routes/oauth2/tokens.ts
diff --git a/api/src/routes/outbound-promotions.ts b/src/api/routes/outbound-promotions.ts
index 411e95bf..411e95bf 100644
--- a/api/src/routes/outbound-promotions.ts
+++ b/src/api/routes/outbound-promotions.ts
diff --git a/api/src/routes/partners/#guild_id/requirements.ts b/src/api/routes/partners/#guild_id/requirements.ts
index 545c5c78..545c5c78 100644
--- a/api/src/routes/partners/#guild_id/requirements.ts
+++ b/src/api/routes/partners/#guild_id/requirements.ts
diff --git a/api/src/routes/ping.ts b/src/api/routes/ping.ts
index 3c1da2c3..3c1da2c3 100644
--- a/api/src/routes/ping.ts
+++ b/src/api/routes/ping.ts
diff --git a/api/src/routes/policies/instance/domains.ts b/src/api/routes/policies/instance/domains.ts
index 20cd07ba..20cd07ba 100644
--- a/api/src/routes/policies/instance/domains.ts
+++ b/src/api/routes/policies/instance/domains.ts
diff --git a/api/src/routes/policies/instance/index.ts b/src/api/routes/policies/instance/index.ts
index e3da014f..e3da014f 100644
--- a/api/src/routes/policies/instance/index.ts
+++ b/src/api/routes/policies/instance/index.ts
diff --git a/api/src/routes/policies/instance/limits.ts b/src/api/routes/policies/instance/limits.ts
index 7de1476b..7de1476b 100644
--- a/api/src/routes/policies/instance/limits.ts
+++ b/src/api/routes/policies/instance/limits.ts
diff --git a/api/src/routes/scheduled-maintenances/upcoming_json.ts b/src/api/routes/scheduled-maintenances/upcoming_json.ts
index 83092e44..83092e44 100644
--- a/api/src/routes/scheduled-maintenances/upcoming_json.ts
+++ b/src/api/routes/scheduled-maintenances/upcoming_json.ts
diff --git a/api/src/routes/science.ts b/src/api/routes/science.ts
index 8556a3ad..8556a3ad 100644
--- a/api/src/routes/science.ts
+++ b/src/api/routes/science.ts
diff --git a/api/src/routes/stage-instances.ts b/src/api/routes/stage-instances.ts
index 411e95bf..411e95bf 100644
--- a/api/src/routes/stage-instances.ts
+++ b/src/api/routes/stage-instances.ts
diff --git a/api/src/routes/sticker-packs/index.ts b/src/api/routes/sticker-packs/index.ts
index e6560d12..e6560d12 100644
--- a/api/src/routes/sticker-packs/index.ts
+++ b/src/api/routes/sticker-packs/index.ts
diff --git a/api/src/routes/stickers/#sticker_id/index.ts b/src/api/routes/stickers/#sticker_id/index.ts
index 293ca089..b484a7a1 100644
--- a/api/src/routes/stickers/#sticker_id/index.ts
+++ b/src/api/routes/stickers/#sticker_id/index.ts
@@ -6,7 +6,7 @@ const router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { sticker_id } = req.params;
- res.json(await Sticker.find({ id: sticker_id }));
+ res.json(await Sticker.find({ where: { id: sticker_id } }));
});
export default router;
diff --git a/api/src/routes/stop.ts b/src/api/routes/stop.ts
index 7f8b78ba..7f8b78ba 100644
--- a/api/src/routes/stop.ts
+++ b/src/api/routes/stop.ts
diff --git a/api/src/routes/store/published-listings/applications.ts b/src/api/routes/store/published-listings/applications.ts
index 060a4c3d..060a4c3d 100644
--- a/api/src/routes/store/published-listings/applications.ts
+++ b/src/api/routes/store/published-listings/applications.ts
diff --git a/api/src/routes/store/published-listings/applications/#id/subscription-plans.ts b/src/api/routes/store/published-listings/applications/#id/subscription-plans.ts
index 54151ae5..54151ae5 100644
--- a/api/src/routes/store/published-listings/applications/#id/subscription-plans.ts
+++ b/src/api/routes/store/published-listings/applications/#id/subscription-plans.ts
diff --git a/api/src/routes/store/published-listings/skus.ts b/src/api/routes/store/published-listings/skus.ts
index 060a4c3d..060a4c3d 100644
--- a/api/src/routes/store/published-listings/skus.ts
+++ b/src/api/routes/store/published-listings/skus.ts
diff --git a/api/src/routes/store/published-listings/skus/#sku_id/subscription-plans.ts b/src/api/routes/store/published-listings/skus/#sku_id/subscription-plans.ts
index 03162ec8..03162ec8 100644
--- a/api/src/routes/store/published-listings/skus/#sku_id/subscription-plans.ts
+++ b/src/api/routes/store/published-listings/skus/#sku_id/subscription-plans.ts
diff --git a/api/src/routes/teams.ts b/src/api/routes/teams.ts
index 7ce3abcb..7ce3abcb 100644
--- a/api/src/routes/teams.ts
+++ b/src/api/routes/teams.ts
diff --git a/api/src/routes/template.ts.disabled b/src/api/routes/template.ts.disabled
index fcc59ef4..fcc59ef4 100644
--- a/api/src/routes/template.ts.disabled
+++ b/src/api/routes/template.ts.disabled
diff --git a/api/src/routes/track.ts b/src/api/routes/track.ts
index 8556a3ad..8556a3ad 100644
--- a/api/src/routes/track.ts
+++ b/src/api/routes/track.ts
diff --git a/api/src/routes/updates.ts b/src/api/routes/updates.ts
index cb4577c8..42f77323 100644
--- a/api/src/routes/updates.ts
+++ b/src/api/routes/updates.ts
@@ -7,14 +7,14 @@ const router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
const { client } = Config.get();
- const release = await Release.findOneOrFail({ name: client.releases.upstreamVersion})
+ const release = await Release.findOneOrFail({ where: { name: client.releases.upstreamVersion } });
res.json({
- name: release.name,
- pub_date: release.pub_date,
- url: release.url,
- notes: release.notes
- });
+ name: release.name,
+ pub_date: release.pub_date,
+ url: release.url,
+ notes: release.notes
+ });
});
export default router;
diff --git a/api/src/routes/users/#id/index.ts b/src/api/routes/users/#id/index.ts
index bdb1060f..bdb1060f 100644
--- a/api/src/routes/users/#id/index.ts
+++ b/src/api/routes/users/#id/index.ts
diff --git a/api/src/routes/users/#id/profile.ts b/src/api/routes/users/#id/profile.ts
index a77fbdb5..de96422a 100644
--- a/api/src/routes/users/#id/profile.ts
+++ b/src/api/routes/users/#id/profile.ts
@@ -22,8 +22,8 @@ router.get("/", route({ test: { response: { body: "UserProfileResponse" } } }),
var premium_guild_since;
if (with_mutual_guilds == "true") {
- const requested_member = await Member.find({ id: req.params.id, });
- const self_member = await Member.find({ id: req.user_id, });
+ const requested_member = await Member.find({ where: { id: req.params.id } });
+ const self_member = await Member.find({ where: { id: req.user_id } });
for (const rmem of requested_member) {
if (rmem.premium_since) {
@@ -44,7 +44,7 @@ router.get("/", route({ test: { response: { body: "UserProfileResponse" } } }),
}
const guild_member = guild_id && typeof guild_id == "string"
- ? await Member.findOneOrFail({ id: req.params.id, guild_id: guild_id }, { relations: ["roles"] })
+ ? await Member.findOneOrFail({ where: { id: req.params.id, guild_id: guild_id }, relations: ["roles"] })
: undefined;
// TODO: make proper DTO's in util?
diff --git a/api/src/routes/users/#id/relationships.ts b/src/api/routes/users/#id/relationships.ts
index de7cb9d3..de7cb9d3 100644
--- a/api/src/routes/users/#id/relationships.ts
+++ b/src/api/routes/users/#id/relationships.ts
diff --git a/api/src/routes/users/@me/activities/statistics/applications.ts b/src/api/routes/users/@me/activities/statistics/applications.ts
index 014df8af..014df8af 100644
--- a/api/src/routes/users/@me/activities/statistics/applications.ts
+++ b/src/api/routes/users/@me/activities/statistics/applications.ts
diff --git a/api/src/routes/users/@me/affinities/guilds.ts b/src/api/routes/users/@me/affinities/guilds.ts
index 8d744744..8d744744 100644
--- a/api/src/routes/users/@me/affinities/guilds.ts
+++ b/src/api/routes/users/@me/affinities/guilds.ts
diff --git a/api/src/routes/users/@me/affinities/users.ts b/src/api/routes/users/@me/affinities/users.ts
index 6d4e4991..6d4e4991 100644
--- a/api/src/routes/users/@me/affinities/users.ts
+++ b/src/api/routes/users/@me/affinities/users.ts
diff --git a/api/src/routes/users/@me/applications/#app_id/entitlements.ts b/src/api/routes/users/@me/applications/#app_id/entitlements.ts
index 411e95bf..411e95bf 100644
--- a/api/src/routes/users/@me/applications/#app_id/entitlements.ts
+++ b/src/api/routes/users/@me/applications/#app_id/entitlements.ts
diff --git a/api/src/routes/users/@me/billing/country-code.ts b/src/api/routes/users/@me/billing/country-code.ts
index 33d40796..33d40796 100644
--- a/api/src/routes/users/@me/billing/country-code.ts
+++ b/src/api/routes/users/@me/billing/country-code.ts
diff --git a/api/src/routes/users/@me/billing/payment-sources.ts b/src/api/routes/users/@me/billing/payment-sources.ts
index 014df8af..014df8af 100644
--- a/api/src/routes/users/@me/billing/payment-sources.ts
+++ b/src/api/routes/users/@me/billing/payment-sources.ts
diff --git a/api/src/routes/users/@me/billing/subscriptions.ts b/src/api/routes/users/@me/billing/subscriptions.ts
index 411e95bf..411e95bf 100644
--- a/api/src/routes/users/@me/billing/subscriptions.ts
+++ b/src/api/routes/users/@me/billing/subscriptions.ts
diff --git a/api/src/routes/users/@me/channels.ts b/src/api/routes/users/@me/channels.ts
index 78f531e1..78f531e1 100644
--- a/api/src/routes/users/@me/channels.ts
+++ b/src/api/routes/users/@me/channels.ts
diff --git a/api/src/routes/users/@me/connections.ts b/src/api/routes/users/@me/connections.ts
index 411e95bf..411e95bf 100644
--- a/api/src/routes/users/@me/connections.ts
+++ b/src/api/routes/users/@me/connections.ts
diff --git a/api/src/routes/users/@me/delete.ts b/src/api/routes/users/@me/delete.ts
index c24c3f1e..c24c3f1e 100644
--- a/api/src/routes/users/@me/delete.ts
+++ b/src/api/routes/users/@me/delete.ts
diff --git a/api/src/routes/users/@me/devices.ts b/src/api/routes/users/@me/devices.ts
index 8556a3ad..8556a3ad 100644
--- a/api/src/routes/users/@me/devices.ts
+++ b/src/api/routes/users/@me/devices.ts
diff --git a/api/src/routes/users/@me/disable.ts b/src/api/routes/users/@me/disable.ts
index 4aff3774..4aff3774 100644
--- a/api/src/routes/users/@me/disable.ts
+++ b/src/api/routes/users/@me/disable.ts
diff --git a/api/src/routes/users/@me/email-settings.ts b/src/api/routes/users/@me/email-settings.ts
index 3114984e..3114984e 100644
--- a/api/src/routes/users/@me/email-settings.ts
+++ b/src/api/routes/users/@me/email-settings.ts
diff --git a/api/src/routes/users/@me/entitlements.ts b/src/api/routes/users/@me/entitlements.ts
index 341e2b4c..341e2b4c 100644
--- a/api/src/routes/users/@me/entitlements.ts
+++ b/src/api/routes/users/@me/entitlements.ts
diff --git a/api/src/routes/users/@me/guilds.ts b/src/api/routes/users/@me/guilds.ts
index 754a240e..754a240e 100644
--- a/api/src/routes/users/@me/guilds.ts
+++ b/src/api/routes/users/@me/guilds.ts
diff --git a/api/src/routes/users/@me/guilds/#guild_id/settings.ts b/src/api/routes/users/@me/guilds/#guild_id/settings.ts
index f09be25b..f09be25b 100644
--- a/api/src/routes/users/@me/guilds/#guild_id/settings.ts
+++ b/src/api/routes/users/@me/guilds/#guild_id/settings.ts
diff --git a/api/src/routes/users/@me/guilds/premium/subscription-slots.ts b/src/api/routes/users/@me/guilds/premium/subscription-slots.ts
index 014df8af..014df8af 100644
--- a/api/src/routes/users/@me/guilds/premium/subscription-slots.ts
+++ b/src/api/routes/users/@me/guilds/premium/subscription-slots.ts
diff --git a/api/src/routes/users/@me/index.ts b/src/api/routes/users/@me/index.ts
index 36b62b55..36b62b55 100644
--- a/api/src/routes/users/@me/index.ts
+++ b/src/api/routes/users/@me/index.ts
diff --git a/api/src/routes/users/@me/library.ts b/src/api/routes/users/@me/library.ts
index 7ac13bae..7ac13bae 100644
--- a/api/src/routes/users/@me/library.ts
+++ b/src/api/routes/users/@me/library.ts
diff --git a/api/src/routes/users/@me/mfa/codes-verification.ts b/src/api/routes/users/@me/mfa/codes-verification.ts
index 3aca44a6..09000d07 100644
--- a/api/src/routes/users/@me/mfa/codes-verification.ts
+++ b/src/api/routes/users/@me/mfa/codes-verification.ts
@@ -16,7 +16,7 @@ router.post("/", route({ body: "CodesVerificationSchema" }), async (req: Request
// TODO: We don't have email/etc etc, so can't send a verification code.
// Once that's done, this route can verify `key`
- const user = await User.findOneOrFail({ id: req.user_id });
+ const user = await User.findOneOrFail({ where: { id: req.user_id } });
var codes: BackupCode[];
if (regenerate) {
@@ -30,16 +30,18 @@ router.post("/", route({ body: "CodesVerificationSchema" }), async (req: Request
}
else {
codes = await BackupCode.find({
- user: {
- id: req.user_id,
- },
- expired: false,
+ where: {
+ user: {
+ id: req.user_id,
+ },
+ expired: false,
+ }
});
}
return res.json({
backup_codes: codes.map(x => ({ ...x, expired: undefined })),
- })
+ });
});
export default router;
diff --git a/api/src/routes/users/@me/mfa/codes.ts b/src/api/routes/users/@me/mfa/codes.ts
index 2a1fb498..67bd3d5b 100644
--- a/api/src/routes/users/@me/mfa/codes.ts
+++ b/src/api/routes/users/@me/mfa/codes.ts
@@ -15,7 +15,7 @@ export interface MfaCodesSchema {
router.post("/", route({ body: "MfaCodesSchema" }), async (req: Request, res: Response) => {
const { password, regenerate } = req.body as MfaCodesSchema;
- const user = await User.findOneOrFail({ id: req.user_id }, { select: ["data"] });
+ const user = await User.findOneOrFail({ where: { id: req.user_id }, select: ["data"] });
if (!await bcrypt.compare(password, user.data.hash || "")) {
throw FieldErrors({ password: { message: req.t("auth:login.INVALID_PASSWORD"), code: "INVALID_PASSWORD" } });
@@ -33,16 +33,18 @@ router.post("/", route({ body: "MfaCodesSchema" }), async (req: Request, res: Re
}
else {
codes = await BackupCode.find({
- user: {
- id: req.user_id,
- },
- expired: false,
+ where: {
+ user: {
+ id: req.user_id,
+ },
+ expired: false,
+ }
});
}
return res.json({
backup_codes: codes.map(x => ({ ...x, expired: undefined })),
- })
+ });
});
export default router;
diff --git a/api/src/routes/users/@me/mfa/totp/disable.ts b/src/api/routes/users/@me/mfa/totp/disable.ts
index 5e039ea3..2d385fda 100644
--- a/api/src/routes/users/@me/mfa/totp/disable.ts
+++ b/src/api/routes/users/@me/mfa/totp/disable.ts
@@ -13,9 +13,9 @@ export interface TotpDisableSchema {
router.post("/", route({ body: "TotpDisableSchema" }), async (req: Request, res: Response) => {
const body = req.body as TotpDisableSchema;
- const user = await User.findOneOrFail({ id: req.user_id }, { select: ["totp_secret"] });
+ const user = await User.findOneOrFail({ where: { id: req.user_id }, select: ["totp_secret"] });
- const backup = await BackupCode.findOne({ code: body.code });
+ const backup = await BackupCode.findOne({ where: { code: body.code } });
if (!backup) {
const ret = verifyToken(user.totp_secret!, body.code);
if (!ret || ret.delta != 0)
diff --git a/api/src/routes/users/@me/mfa/totp/enable.ts b/src/api/routes/users/@me/mfa/totp/enable.ts
index e4ce9ce0..e4ce9ce0 100644
--- a/api/src/routes/users/@me/mfa/totp/enable.ts
+++ b/src/api/routes/users/@me/mfa/totp/enable.ts
diff --git a/api/src/routes/users/@me/notes.ts b/src/api/routes/users/@me/notes.ts
index 3c503942..f938f088 100644
--- a/api/src/routes/users/@me/notes.ts
+++ b/src/api/routes/users/@me/notes.ts
@@ -29,7 +29,7 @@ router.put("/:id", route({}), async (req: Request, res: Response) => {
if (note && note.length) {
// upsert a note
- if (await Note.findOne({ owner: { id: owner.id }, target: { id: target.id } })) {
+ if (await Note.findOne({ where: { owner: { id: owner.id }, target: { id: target.id } } })) {
Note.update(
{ owner: { id: owner.id }, target: { id: target.id } },
{ owner, target, content: note }
diff --git a/api/src/routes/users/@me/relationships.ts b/src/api/routes/users/@me/relationships.ts
index c5a643d2..00d4da0b 100644
--- a/api/src/routes/users/@me/relationships.ts
+++ b/src/api/routes/users/@me/relationships.ts
@@ -45,7 +45,7 @@ router.put("/:id", route({ body: "RelationshipPutSchema" }), async (req: Request
return await updateRelationship(
req,
res,
- await User.findOneOrFail({ id: req.params.id }, { relations: ["relationships", "relationships.to"], select: userProjection }),
+ await User.findOneOrFail({ where: { id: req.params.id }, relations: ["relationships", "relationships.to"], select: userProjection }),
req.body.type ?? RelationshipType.friends
);
});
@@ -75,8 +75,8 @@ router.delete("/:id", route({}), async (req: Request, res: Response) => {
const { id } = req.params;
if (id === req.user_id) throw new HTTPError("You can't remove yourself as a friend");
- const user = await User.findOneOrFail({ id: req.user_id }, { select: userProjection, relations: ["relationships"] });
- const friend = await User.findOneOrFail({ id: id }, { select: userProjection, relations: ["relationships"] });
+ const user = await User.findOneOrFail({ where: { id: req.user_id }, select: userProjection, relations: ["relationships"] });
+ const friend = await User.findOneOrFail({ where: { id: id }, select: userProjection, relations: ["relationships"] });
const relationship = user.relationships.find((x) => x.to_id === id);
const friendRequest = friend.relationships.find((x) => x.to_id === req.user_id);
@@ -124,10 +124,10 @@ async function updateRelationship(req: Request, res: Response, friend: User, typ
const id = friend.id;
if (id === req.user_id) throw new HTTPError("You can't add yourself as a friend");
- const user = await User.findOneOrFail(
- { id: req.user_id },
- { relations: ["relationships", "relationships.to"], select: userProjection }
- );
+ const user = await User.findOneOrFail({
+ where: { id: req.user_id },
+ relations: ["relationships", "relationships.to"], select: userProjection
+ });
var relationship = user.relationships.find((x) => x.to_id === id);
const friendRequest = friend.relationships.find((x) => x.to_id === req.user_id);
@@ -139,7 +139,7 @@ async function updateRelationship(req: Request, res: Response, friend: User, typ
relationship.type = RelationshipType.blocked;
await relationship.save();
} else {
- relationship = await new Relationship({ to_id: id, type: RelationshipType.blocked, from_id: req.user_id }).save();
+ relationship = await Relationship.create({ to_id: id, type: RelationshipType.blocked, from_id: req.user_id }).save();
}
if (friendRequest && friendRequest.type !== RelationshipType.blocked) {
@@ -165,8 +165,8 @@ async function updateRelationship(req: Request, res: Response, friend: User, typ
const { maxFriends } = Config.get().limits.user;
if (user.relationships.length >= maxFriends) throw DiscordApiErrors.MAXIMUM_FRIENDS.withParams(maxFriends);
- var incoming_relationship = new Relationship({ nickname: undefined, type: RelationshipType.incoming, to: user, from: friend });
- var outgoing_relationship = new Relationship({
+ var incoming_relationship = Relationship.create({ nickname: undefined, type: RelationshipType.incoming, to: user, from: friend });
+ var outgoing_relationship = Relationship.create({
nickname: undefined,
type: RelationshipType.outgoing,
to: friend,
diff --git a/api/src/routes/users/@me/settings.ts b/src/api/routes/users/@me/settings.ts
index a03e2fdd..9060baf7 100644
--- a/api/src/routes/users/@me/settings.ts
+++ b/src/api/routes/users/@me/settings.ts
@@ -7,10 +7,10 @@ const router = Router();
export interface UserSettingsSchema extends Partial<UserSettings> { }
router.get("/", route({}), async (req: Request, res: Response) => {
- const user = await User.findOneOrFail(
- { id: req.user_id },
- { select: ["settings"] }
- );
+ const user = await User.findOneOrFail({
+ where: { id: req.user_id },
+ select: ["settings"]
+ });
return res.json(user.settings);
});
@@ -18,7 +18,7 @@ router.patch("/", route({ body: "UserSettingsSchema" }), async (req: Request, re
const body = req.body as UserSettings;
if (body.locale === "en") body.locale = "en-US"; // fix discord client crash on unkown locale
- const user = await User.findOneOrFail({ id: req.user_id, bot: false });
+ const user = await User.findOneOrFail({ where: { id: req.user_id, bot: false } });
user.settings = { ...user.settings, ...body };
await user.save();
diff --git a/api/src/routes/voice/regions.ts b/src/api/routes/voice/regions.ts
index 4de304ee..4de304ee 100644
--- a/api/src/routes/voice/regions.ts
+++ b/src/api/routes/voice/regions.ts
diff --git a/api/src/start.ts b/src/api/start.ts
index ccb4d108..ccb4d108 100644
--- a/api/src/start.ts
+++ b/src/api/start.ts
diff --git a/api/src/util/entities/blockedEmailDomains.txt b/src/api/util/entities/blockedEmailDomains.txt
index eb88305d..eb88305d 100644
--- a/api/src/util/entities/blockedEmailDomains.txt
+++ b/src/api/util/entities/blockedEmailDomains.txt
diff --git a/api/src/util/entities/trustedEmailDomains.txt b/src/api/util/entities/trustedEmailDomains.txt
index 38ffa4fa..38ffa4fa 100644
--- a/api/src/util/entities/trustedEmailDomains.txt
+++ b/src/api/util/entities/trustedEmailDomains.txt
diff --git a/api/src/util/handlers/Instance.ts b/src/api/util/handlers/Instance.ts
index 6bddfa98..fa134fd8 100644
--- a/api/src/util/handlers/Instance.ts
+++ b/src/api/util/handlers/Instance.ts
@@ -9,7 +9,7 @@ export async function initInstance() {
const { autoJoin } = Config.get().guild;
if (autoJoin.enabled && !autoJoin.guilds?.length) {
- let guild = await Guild.findOne({});
+ let guild = await Guild.findOne({ where: {}, select: ["id"] });
if (guild) {
// @ts-ignore
await Config.set({ guild: { autoJoin: { guilds: [guild.id] } } });
diff --git a/api/src/util/handlers/Message.ts b/src/api/util/handlers/Message.ts
index 398b8914..7e91fb7b 100644
--- a/api/src/util/handlers/Message.ts
+++ b/src/api/util/handlers/Message.ts
@@ -21,11 +21,13 @@ import {
Webhook,
Attachment,
Config,
+ Sticker,
} from "@fosscord/util";
import { HTTPError } from "lambert-server";
import fetch from "node-fetch";
import cheerio from "cheerio";
import { MessageCreateSchema } from "../../routes/channels/#channel_id/messages";
+import { In } from "typeorm";
const allow_empty = false;
// TODO: check webhook, application, system author, stickers
// TODO: embed gifs/videos/images
@@ -47,9 +49,11 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
const channel = await Channel.findOneOrFail({ where: { id: opts.channel_id }, relations: ["recipients"] });
if (!channel || !opts.channel_id) throw new HTTPError("Channel not found", 404);
- const message = new Message({
+ const stickers = opts.sticker_ids ? await Sticker.find({ where: { id: In(opts.sticker_ids) } }) : undefined;
+ const message = Message.create({
...opts,
- sticker_items: opts.sticker_ids?.map((x) => ({ id: x })),
+ id: Snowflake.generate(),
+ sticker_items: stickers,
guild_id: channel.guild_id,
channel_id: opts.channel_id,
attachments: opts.attachments || [],
@@ -68,10 +72,10 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
rights.hasThrow("SEND_MESSAGES");
}
if (opts.application_id) {
- message.application = await Application.findOneOrFail({ id: opts.application_id });
+ message.application = await Application.findOneOrFail({ where: { id: opts.application_id } });
}
if (opts.webhook_id) {
- message.webhook = await Webhook.findOneOrFail({ id: opts.webhook_id });
+ message.webhook = await Webhook.findOneOrFail({ where: { id: opts.webhook_id } });
}
const permission = await getPermission(opts.author_id, channel.guild_id, opts.channel_id);
@@ -85,7 +89,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
permission.hasThrow("READ_MESSAGE_HISTORY");
// code below has to be redone when we add custom message routing
if (message.guild_id !== null) {
- const guild = await Guild.findOneOrFail({ id: channel.guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: channel.guild_id } });
if (!guild.features.includes("CROSS_CHANNEL_REPLIES")) {
if (opts.message_reference.guild_id !== channel.guild_id) throw new HTTPError("You can only reference messages from this guild");
if (opts.message_reference.channel_id !== opts.channel_id) throw new HTTPError("You can only reference messages from this channel");
@@ -120,7 +124,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
await Promise.all(
Array.from(content.matchAll(ROLE_MENTION)).map(async ([_, mention]) => {
- const role = await Role.findOneOrFail({ id: mention, guild_id: channel.guild_id });
+ const role = await Role.findOneOrFail({ where: { id: mention, guild_id: channel.guild_id } });
if (role.mentionable || permission.has("MANAGE_ROLES")) {
mention_role_ids.push(mention);
}
@@ -132,9 +136,9 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
}
}
- message.mention_channels = mention_channel_ids.map((x) => new Channel({ id: x }));
- message.mention_roles = mention_role_ids.map((x) => new Role({ id: x }));
- message.mentions = mention_user_ids.map((x) => new User({ id: x }));
+ message.mention_channels = mention_channel_ids.map((x) => Channel.create({ id: x }));
+ message.mention_roles = mention_role_ids.map((x) => Role.create({ id: x }));
+ message.mentions = mention_user_ids.map((x) => User.create({ id: x }));
message.mention_everyone = mention_everyone;
// TODO: check and put it all in the body
@@ -278,6 +282,6 @@ interface MessageOptions extends MessageCreateSchema {
embeds?: Embed[];
channel_id?: string;
attachments?: Attachment[];
- edited_timestamp: Date | null;
+ edited_timestamp?: Date;
timestamp?: Date;
}
diff --git a/api/src/util/handlers/Voice.ts b/src/api/util/handlers/Voice.ts
index 4d60eb91..4d60eb91 100644
--- a/api/src/util/handlers/Voice.ts
+++ b/src/api/util/handlers/Voice.ts
diff --git a/api/src/util/handlers/route.ts b/src/api/util/handlers/route.ts
index 3d3bbc37..c245b411 100644
--- a/api/src/util/handlers/route.ts
+++ b/src/api/util/handlers/route.ts
@@ -1,39 +1,19 @@
import {
+ ajv,
DiscordApiErrors,
EVENT,
- Event,
- EventData,
FieldErrors,
FosscordApiErrors,
getPermission,
getRights,
+ normalizeBody,
PermissionResolvable,
Permissions,
RightResolvable,
Rights
} from "@fosscord/util";
import { NextFunction, Request, Response } from "express";
-import fs from "fs";
-import path from "path";
-import Ajv from "ajv";
import { AnyValidateFunction } from "ajv/dist/core";
-import addFormats from "ajv-formats";
-
-const SchemaPath = path.join(__dirname, "..", "..", "..", "assets", "schemas.json");
-const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
-
-export const ajv = new Ajv({
- allErrors: true,
- parseDate: true,
- allowDate: true,
- schemas,
- coerceTypes: true,
- messages: true,
- strict: true,
- strictRequired: true
-});
-
-addFormats(ajv);
declare global {
namespace Express {
@@ -58,34 +38,6 @@ export interface RouteOptions {
};
}
-// Normalizer is introduced to workaround https://github.com/ajv-validator/ajv/issues/1287
-// this removes null values as ajv doesn't treat them as undefined
-// normalizeBody allows to handle circular structures without issues
-// taken from https://github.com/serverless/serverless/blob/master/lib/classes/ConfigSchemaHandler/index.js#L30 (MIT license)
-const normalizeBody = (body: any = {}) => {
- const normalizedObjectsSet = new WeakSet();
- const normalizeObject = (object: any) => {
- if (normalizedObjectsSet.has(object)) return;
- normalizedObjectsSet.add(object);
- if (Array.isArray(object)) {
- for (const [index, value] of object.entries()) {
- if (typeof value === "object") normalizeObject(value);
- }
- } else {
- for (const [key, value] of Object.entries(object)) {
- if (value == null) {
- if (key === "icon" || key === "avatar" || key === "banner" || key === "splash" || key === "discovery_splash") continue;
- delete object[key];
- } else if (typeof value === "object") {
- normalizeObject(value);
- }
- }
- }
- };
- normalizeObject(body);
- return body;
-};
-
export function route(opts: RouteOptions) {
var validate: AnyValidateFunction<any> | undefined;
if (opts.body) {
diff --git a/api/src/util/index.ts b/src/api/util/index.ts
index de6b6064..de6b6064 100644
--- a/api/src/util/index.ts
+++ b/src/api/util/index.ts
diff --git a/api/src/util/utility/Base64.ts b/src/api/util/utility/Base64.ts
index 46cff77a..46cff77a 100644
--- a/api/src/util/utility/Base64.ts
+++ b/src/api/util/utility/Base64.ts
diff --git a/api/src/util/utility/RandomInviteID.ts b/src/api/util/utility/RandomInviteID.ts
index 7ea344e0..7ea344e0 100644
--- a/api/src/util/utility/RandomInviteID.ts
+++ b/src/api/util/utility/RandomInviteID.ts
diff --git a/api/src/util/utility/String.ts b/src/api/util/utility/String.ts
index 982b7e11..982b7e11 100644
--- a/api/src/util/utility/String.ts
+++ b/src/api/util/utility/String.ts
diff --git a/api/src/util/utility/captcha.ts b/src/api/util/utility/captcha.ts
index 739647d2..739647d2 100644
--- a/api/src/util/utility/captcha.ts
+++ b/src/api/util/utility/captcha.ts
diff --git a/api/src/util/utility/ipAddress.ts b/src/api/util/utility/ipAddress.ts
index 13cc9603..f17b145e 100644
--- a/api/src/util/utility/ipAddress.ts
+++ b/src/api/util/utility/ipAddress.ts
@@ -65,7 +65,7 @@ export async function IPAnalysis(ip: string): Promise<typeof exampleData> {
const { ipdataApiKey } = Config.get().security;
if (!ipdataApiKey) return { ...exampleData, ip };
- return (await fetch(`https://api.ipdata.co/${ip}?api-key=${ipdataApiKey}`)).json();
+ return (await fetch(`https://api.ipdata.co/${ip}?api-key=${ipdataApiKey}`)).json() as any; // TODO: types
}
export function isProxy(data: typeof exampleData) {
diff --git a/api/src/util/utility/passwordStrength.ts b/src/api/util/utility/passwordStrength.ts
index 439700d0..439700d0 100644
--- a/api/src/util/utility/passwordStrength.ts
+++ b/src/api/util/utility/passwordStrength.ts
diff --git a/bundle/src/Server.ts b/src/bundle/Server.ts
index da810d9b..da810d9b 100644
--- a/bundle/src/Server.ts
+++ b/src/bundle/Server.ts
diff --git a/src/bundle/index.ts b/src/bundle/index.ts
new file mode 100644
index 00000000..960d4dc0
--- /dev/null
+++ b/src/bundle/index.ts
@@ -0,0 +1,4 @@
+export * from "@fosscord/api";
+export * from "@fosscord/util";
+export * from "@fosscord/gateway";
+export * from "@fosscord/cdn";
\ No newline at end of file
diff --git a/bundle/src/start.ts b/src/bundle/start.ts
index de3b5848..2a1e6520 100644
--- a/bundle/src/start.ts
+++ b/src/bundle/start.ts
@@ -1,4 +1,5 @@
// process.env.MONGOMS_DEBUG = "true";
+require('module-alias/register');
import "reflect-metadata";
import cluster, { Worker } from "cluster";
import os from "os";
@@ -13,7 +14,7 @@ var cores = 1;
try {
cores = Number(process.env.THREADS) || os.cpus().length;
} catch {
- console.log("[API] Failed to get thread count! Using 1...")
+ console.log("[API] Failed to get thread count! Using 1...");
}
if (cluster.isMaster) {
@@ -36,18 +37,16 @@ if (cluster.isMaster) {
╚═╝ ╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝
fosscord-server | ${yellow(
- `Pre-release (${
- commit !== null
- ? commit.slice(0, 7)
- : "Unknown (Git cannot be found)"
+ `Pre-release (${commit !== null
+ ? commit.slice(0, 7)
+ : "Unknown (Git cannot be found)"
})`
)}
-Commit Hash: ${
- commit !== null
+Commit Hash: ${commit !== null
? `${cyan(commit)} (${yellow(commit.slice(0, 7))})`
: "Unknown (Git cannot be found)"
- }
+ }
Cores: ${cyan(os.cpus().length)} (Using ${cores} thread(s).)
`)
);
diff --git a/bundle/src/stats.ts b/src/bundle/stats.ts
index 0234e0b4..0234e0b4 100644
--- a/bundle/src/stats.ts
+++ b/src/bundle/stats.ts
diff --git a/cdn/src/Server.ts b/src/cdn/Server.ts
index 5b395589..5b395589 100644
--- a/cdn/src/Server.ts
+++ b/src/cdn/Server.ts
diff --git a/cdn/src/index.ts b/src/cdn/index.ts
index a24300d6..a24300d6 100644
--- a/cdn/src/index.ts
+++ b/src/cdn/index.ts
diff --git a/cdn/src/routes/attachments.ts b/src/cdn/routes/attachments.ts
index ae50bc48..ae50bc48 100644
--- a/cdn/src/routes/attachments.ts
+++ b/src/cdn/routes/attachments.ts
diff --git a/cdn/src/routes/avatars.ts b/src/cdn/routes/avatars.ts
index e5e25a4c..e5e25a4c 100644
--- a/cdn/src/routes/avatars.ts
+++ b/src/cdn/routes/avatars.ts
diff --git a/cdn/src/routes/external.ts b/src/cdn/routes/external.ts
index fc12c017..cb17ff9b 100644
--- a/cdn/src/routes/external.ts
+++ b/src/cdn/routes/external.ts
@@ -3,7 +3,7 @@ import fetch from "node-fetch";
import { HTTPError } from "lambert-server";
import { Snowflake } from "@fosscord/util";
import { storage } from "../util/Storage";
-import FileType, { stream } from "file-type";
+import FileType from "file-type";
import { Config } from "@fosscord/util";
import sharp from "sharp";
diff --git a/cdn/src/routes/guilds.ts b/src/cdn/routes/guilds.ts
index 3c4b646c..3c4b646c 100644
--- a/cdn/src/routes/guilds.ts
+++ b/src/cdn/routes/guilds.ts
diff --git a/cdn/src/routes/ping.ts b/src/cdn/routes/ping.ts
index 38daf81e..38daf81e 100644
--- a/cdn/src/routes/ping.ts
+++ b/src/cdn/routes/ping.ts
diff --git a/cdn/src/routes/role-icons.ts b/src/cdn/routes/role-icons.ts
index 12aae8a4..12aae8a4 100644
--- a/cdn/src/routes/role-icons.ts
+++ b/src/cdn/routes/role-icons.ts
diff --git a/cdn/src/start.ts b/src/cdn/start.ts
index 71681b40..1fdea22e 100644
--- a/cdn/src/start.ts
+++ b/src/cdn/start.ts
@@ -1,3 +1,4 @@
+require('module-alias/register')
import dotenv from "dotenv";
dotenv.config();
diff --git a/cdn/src/util/FileStorage.ts b/src/cdn/util/FileStorage.ts
index 84ecf556..955c570b 100644
--- a/cdn/src/util/FileStorage.ts
+++ b/src/cdn/util/FileStorage.ts
@@ -1,10 +1,9 @@
import { Storage } from "./Storage";
import fs from "fs";
-import fse from "fs-extra";
import { join, relative, dirname } from "path";
import "missing-native-js-functions";
import { Readable } from "stream";
-import ExifTransformer = require("exif-be-gone");
+import ExifTransformer from "exif-be-gone";
// TODO: split stored files into separate folders named after cloned route
@@ -36,7 +35,7 @@ export class FileStorage implements Storage {
async set(path: string, value: any) {
path = getPath(path);
- fse.ensureDirSync(dirname(path));
+ if (!fs.existsSync(dirname(path))) fs.mkdirSync(dirname(path));
value = Readable.from(value);
const cleaned_file = fs.createWriteStream(path);
diff --git a/cdn/src/util/S3Storage.ts b/src/cdn/util/S3Storage.ts
index c4066817..c4066817 100644
--- a/cdn/src/util/S3Storage.ts
+++ b/src/cdn/util/S3Storage.ts
diff --git a/cdn/src/util/Storage.ts b/src/cdn/util/Storage.ts
index 89dd5634..04fbacca 100644
--- a/cdn/src/util/Storage.ts
+++ b/src/cdn/util/Storage.ts
@@ -1,6 +1,6 @@
import { FileStorage } from "./FileStorage";
import path from "path";
-import fse from "fs-extra";
+import fs from "fs";
import { bgCyan, black } from "picocolors";
import { S3 } from "@aws-sdk/client-s3";
import { S3Storage } from "./S3Storage";
@@ -22,7 +22,7 @@ if (process.env.STORAGE_PROVIDER === "file" || !process.env.STORAGE_PROVIDER) {
location = path.join(process.cwd(), "files");
}
console.log(`[CDN] storage location: ${bgCyan(`${black(location)}`)}`);
- fse.ensureDirSync(location);
+ if (!fs.existsSync(location)) fs.mkdirSync(location);
process.env.STORAGE_LOCATION = location;
storage = new FileStorage();
diff --git a/cdn/src/util/index.ts b/src/cdn/util/index.ts
index 07a5c31a..07a5c31a 100644
--- a/cdn/src/util/index.ts
+++ b/src/cdn/util/index.ts
diff --git a/cdn/src/util/multer.ts b/src/cdn/util/multer.ts
index bfdf6aff..bfdf6aff 100644
--- a/cdn/src/util/multer.ts
+++ b/src/cdn/util/multer.ts
diff --git a/gateway/src/Server.ts b/src/gateway/Server.ts
index 7e1489be..7e1489be 100644
--- a/gateway/src/Server.ts
+++ b/src/gateway/Server.ts
diff --git a/gateway/src/events/Close.ts b/src/gateway/events/Close.ts
index 40d9a6f7..40d9a6f7 100644
--- a/gateway/src/events/Close.ts
+++ b/src/gateway/events/Close.ts
diff --git a/gateway/src/events/Connection.ts b/src/gateway/events/Connection.ts
index bed3cf44..bed3cf44 100644
--- a/gateway/src/events/Connection.ts
+++ b/src/gateway/events/Connection.ts
diff --git a/gateway/src/events/Message.ts b/src/gateway/events/Message.ts
index b72ffa37..db7dbad2 100644
--- a/gateway/src/events/Message.ts
+++ b/src/gateway/events/Message.ts
@@ -51,22 +51,22 @@ export async function Message(this: WebSocket, buffer: WS.Data) {
return;
}
- const transaction = Sentry.startTransaction({
- op: OPCODES[data.op],
- name: `GATEWAY ${OPCODES[data.op]}`,
- data: {
- ...data.d,
- token: data?.d?.token ? "[Redacted]" : undefined,
- },
- });
+ // const transaction = Sentry.startTransaction({
+ // op: OPCODES[data.op],
+ // name: `GATEWAY ${OPCODES[data.op]}`,
+ // data: {
+ // ...data.d,
+ // token: data?.d?.token ? "[Redacted]" : undefined,
+ // },
+ // });
try {
var ret = await OPCodeHandler.call(this, data);
- transaction.finish();
+ // transaction.finish();
return ret;
} catch (error) {
Sentry.captureException(error);
- transaction.finish();
+ // transaction.finish();
console.error(`Error: Op ${data.op}`, error);
// if (!this.CLOSED && this.CLOSING)
return this.close(CLOSECODES.Unknown_error);
diff --git a/gateway/src/index.ts b/src/gateway/index.ts
index d77ce931..d77ce931 100644
--- a/gateway/src/index.ts
+++ b/src/gateway/index.ts
diff --git a/gateway/src/listener/listener.ts b/src/gateway/listener/listener.ts
index 5975fbb7..72dd9d5b 100644
--- a/gateway/src/listener/listener.ts
+++ b/src/gateway/listener/listener.ts
@@ -51,15 +51,17 @@ export async function setupListener(this: WebSocket) {
relations: ["channel"],
}),
Relationship.find({
- from_id: this.user_id,
- type: RelationshipType.friends,
+ where: {
+ from_id: this.user_id,
+ type: RelationshipType.friends,
+ }
}),
]);
const guilds = members.map((x) => x.guild);
const dm_channels = recipients.map((x) => x.channel);
- const opts: { acknowledge: boolean; channel?: AMQChannel } = {
+ const opts: { acknowledge: boolean; channel?: AMQChannel; } = {
acknowledge: true,
};
this.listen_options = opts;
diff --git a/gateway/src/opcodes/Heartbeat.ts b/src/gateway/opcodes/Heartbeat.ts
index 50394130..50394130 100644
--- a/gateway/src/opcodes/Heartbeat.ts
+++ b/src/gateway/opcodes/Heartbeat.ts
diff --git a/gateway/src/opcodes/Identify.ts b/src/gateway/opcodes/Identify.ts
index 903934ce..3c40962c 100644
--- a/gateway/src/opcodes/Identify.ts
+++ b/src/gateway/opcodes/Identify.ts
@@ -62,7 +62,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
relations: ["relationships", "relationships.to"],
select: [...PrivateUserProjection, "relationships"],
}),
- ReadState.find({ user_id: this.user_id }),
+ ReadState.find({ where: { user_id: this.user_id } }),
Member.find({
where: { id: this.user_id },
select: MemberPrivateProjection,
@@ -87,7 +87,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
// TODO: public user selection
}),
// save the session and delete it when the websocket is closed
- new Session({
+ Session.create({
user_id: this.user_id,
session_id: session_id,
// TODO: check if status is only one of: online, dnd, offline, idle
@@ -100,7 +100,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
},
activities: [],
}).save(),
- Application.findOne({ id: this.user_id }),
+ Application.findOne({ where: { id: this.user_id } }),
]);
if (!user) return this.close(CLOSECODES.Authentication_failed);
diff --git a/gateway/src/opcodes/LazyRequest.ts b/src/gateway/opcodes/LazyRequest.ts
index b0332969..82342224 100644
--- a/gateway/src/opcodes/LazyRequest.ts
+++ b/src/gateway/opcodes/LazyRequest.ts
@@ -1,12 +1,7 @@
-import { getPermission, listenEvent, Member, Role, Session } from "@fosscord/util";
+import { getDatabase, getPermission, listenEvent, Member, Role, Session } from "@fosscord/util";
+import { WebSocket, Payload, handlePresenceUpdate, OPCODES, Send } from "@fosscord/gateway";
import { LazyRequest } from "../schema/LazyRequest";
-import { Send } from "../util/Send";
-import { OPCODES } from "../util/Constants";
-import { WebSocket, Payload, handlePresenceUpdate } from "@fosscord/gateway";
import { check } from "./instanceOf";
-import "missing-native-js-functions";
-import { getRepository } from "typeorm";
-import "missing-native-js-functions";
// TODO: only show roles/members that have access to this channel
// TODO: config: to list all members (even those who are offline) sorted by role, or just those who are online
@@ -20,7 +15,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
let members: Member[] = [];
try {
- members = await getRepository(Member)
+ members = await getDatabase()!.getRepository(Member)
.createQueryBuilder("member")
.where("member.guild_id = :guild_id", { guild_id })
.leftJoinAndSelect("member.roles", "role")
@@ -34,8 +29,8 @@ async function getMembers(guild_id: string, range: [number, number]) {
.orderBy("role.position", "DESC")
.addOrderBy("_status", "DESC")
.addOrderBy("user.username", "ASC")
- .skip(Number(range[0]) || 0)
- .take(Number(range[1]) || 100)
+ .offset(Number(range[0]) || 0)
+ .limit(Number(range[1]) || 100)
.getMany();
}
catch (e) {
diff --git a/gateway/src/opcodes/PresenceUpdate.ts b/src/gateway/opcodes/PresenceUpdate.ts
index 415df6ee..415df6ee 100644
--- a/gateway/src/opcodes/PresenceUpdate.ts
+++ b/src/gateway/opcodes/PresenceUpdate.ts
diff --git a/gateway/src/opcodes/RequestGuildMembers.ts b/src/gateway/opcodes/RequestGuildMembers.ts
index b80721dc..b80721dc 100644
--- a/gateway/src/opcodes/RequestGuildMembers.ts
+++ b/src/gateway/opcodes/RequestGuildMembers.ts
diff --git a/gateway/src/opcodes/Resume.ts b/src/gateway/opcodes/Resume.ts
index 42dc586d..42dc586d 100644
--- a/gateway/src/opcodes/Resume.ts
+++ b/src/gateway/opcodes/Resume.ts
diff --git a/gateway/src/opcodes/VoiceStateUpdate.ts b/src/gateway/opcodes/VoiceStateUpdate.ts
index ec4b1a92..fa63f7fc 100644
--- a/gateway/src/opcodes/VoiceStateUpdate.ts
+++ b/src/gateway/opcodes/VoiceStateUpdate.ts
@@ -49,7 +49,7 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) {
if (body.guild_id === null) body.guild_id = voiceState.guild_id;
voiceState.assign(body);
} catch (error) {
- voiceState = new VoiceState({
+ voiceState = VoiceState.create({
...body,
user_id: this.user_id,
deaf: false,
@@ -68,7 +68,7 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) {
where: { id: voiceState.user_id, guild_id: voiceState.guild_id },
relations: ["user", "roles"],
});
-
+
//If the session changed we generate a new token
if (voiceState.session_id !== this.session_id)
voiceState.token = genVoiceToken();
@@ -87,7 +87,7 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) {
//If it's null it means that we are leaving the channel and this event is not needed
if (voiceState.channel_id !== null) {
- const guild = await Guild.findOne({ id: voiceState.guild_id });
+ const guild = await Guild.findOne({ where: { id: voiceState.guild_id } });
const regions = Config.get().regions;
let guildRegion: Region;
if (guild && guild.region) {
diff --git a/gateway/src/opcodes/experiments.json b/src/gateway/opcodes/experiments.json
index 0370b5da..0370b5da 100644
--- a/gateway/src/opcodes/experiments.json
+++ b/src/gateway/opcodes/experiments.json
diff --git a/gateway/src/opcodes/index.ts b/src/gateway/opcodes/index.ts
index 027739db..027739db 100644
--- a/gateway/src/opcodes/index.ts
+++ b/src/gateway/opcodes/index.ts
diff --git a/gateway/src/opcodes/instanceOf.ts b/src/gateway/opcodes/instanceOf.ts
index 6fd50852..6fd50852 100644
--- a/gateway/src/opcodes/instanceOf.ts
+++ b/src/gateway/opcodes/instanceOf.ts
diff --git a/gateway/src/schema/Activity.ts b/src/gateway/schema/Activity.ts
index f58b0fa9..f58b0fa9 100644
--- a/gateway/src/schema/Activity.ts
+++ b/src/gateway/schema/Activity.ts
diff --git a/gateway/src/schema/Identify.ts b/src/gateway/schema/Identify.ts
index 6f68b515..6f68b515 100644
--- a/gateway/src/schema/Identify.ts
+++ b/src/gateway/schema/Identify.ts
diff --git a/gateway/src/schema/LazyRequest.ts b/src/gateway/schema/LazyRequest.ts
index 1fe658bb..1fe658bb 100644
--- a/gateway/src/schema/LazyRequest.ts
+++ b/src/gateway/schema/LazyRequest.ts
diff --git a/gateway/src/schema/VoiceStateUpdateSchema.ts b/src/gateway/schema/VoiceStateUpdateSchema.ts
index f6480414..f6480414 100644
--- a/gateway/src/schema/VoiceStateUpdateSchema.ts
+++ b/src/gateway/schema/VoiceStateUpdateSchema.ts
diff --git a/gateway/src/start.ts b/src/gateway/start.ts
index 09a54751..90d7f34e 100644
--- a/gateway/src/start.ts
+++ b/src/gateway/start.ts
@@ -1,3 +1,4 @@
+require('module-alias/register');
process.on("uncaughtException", console.error);
process.on("unhandledRejection", console.error);
diff --git a/gateway/src/util/Constants.ts b/src/gateway/util/Constants.ts
index ff9b5525..ff9b5525 100644
--- a/gateway/src/util/Constants.ts
+++ b/src/gateway/util/Constants.ts
diff --git a/gateway/src/util/Heartbeat.ts b/src/gateway/util/Heartbeat.ts
index f6871cfe..f6871cfe 100644
--- a/gateway/src/util/Heartbeat.ts
+++ b/src/gateway/util/Heartbeat.ts
diff --git a/gateway/src/util/Send.ts b/src/gateway/util/Send.ts
index e1460846..e1460846 100644
--- a/gateway/src/util/Send.ts
+++ b/src/gateway/util/Send.ts
diff --git a/gateway/src/util/SessionUtils.ts b/src/gateway/util/SessionUtils.ts
index bf854042..bf854042 100644
--- a/gateway/src/util/SessionUtils.ts
+++ b/src/gateway/util/SessionUtils.ts
diff --git a/gateway/src/util/WebSocket.ts b/src/gateway/util/WebSocket.ts
index 930fa78a..930fa78a 100644
--- a/gateway/src/util/WebSocket.ts
+++ b/src/gateway/util/WebSocket.ts
diff --git a/gateway/src/util/index.ts b/src/gateway/util/index.ts
index 0be5ecee..0be5ecee 100644
--- a/gateway/src/util/index.ts
+++ b/src/gateway/util/index.ts
diff --git a/util/src/dtos/DmChannelDTO.ts b/src/util/dtos/DmChannelDTO.ts
index 226b2f9d..226b2f9d 100644
--- a/util/src/dtos/DmChannelDTO.ts
+++ b/src/util/dtos/DmChannelDTO.ts
diff --git a/util/src/dtos/UserDTO.ts b/src/util/dtos/UserDTO.ts
index ee2752a4..ee2752a4 100644
--- a/util/src/dtos/UserDTO.ts
+++ b/src/util/dtos/UserDTO.ts
diff --git a/util/src/dtos/index.ts b/src/util/dtos/index.ts
index 0e8f8459..0e8f8459 100644
--- a/util/src/dtos/index.ts
+++ b/src/util/dtos/index.ts
diff --git a/util/src/entities/Application.ts b/src/util/entities/Application.ts
index fab3d93f..fab3d93f 100644
--- a/util/src/entities/Application.ts
+++ b/src/util/entities/Application.ts
diff --git a/util/src/entities/Attachment.ts b/src/util/entities/Attachment.ts
index 7b4b17eb..7b4b17eb 100644
--- a/util/src/entities/Attachment.ts
+++ b/src/util/entities/Attachment.ts
diff --git a/util/src/entities/AuditLog.ts b/src/util/entities/AuditLog.ts
index b003e7ba..b003e7ba 100644
--- a/util/src/entities/AuditLog.ts
+++ b/src/util/entities/AuditLog.ts
diff --git a/util/src/entities/BackupCodes.ts b/src/util/entities/BackupCodes.ts
index d532a39a..d532a39a 100644
--- a/util/src/entities/BackupCodes.ts
+++ b/src/util/entities/BackupCodes.ts
diff --git a/util/src/entities/Ban.ts b/src/util/entities/Ban.ts
index 9504bd8e..9504bd8e 100644
--- a/util/src/entities/Ban.ts
+++ b/src/util/entities/Ban.ts
diff --git a/src/util/entities/BaseClass.ts b/src/util/entities/BaseClass.ts
new file mode 100644
index 00000000..d5a7c2bf
--- /dev/null
+++ b/src/util/entities/BaseClass.ts
@@ -0,0 +1,52 @@
+import "reflect-metadata";
+import { BaseEntity, BeforeInsert, BeforeUpdate, FindOptionsWhere, ObjectIdColumn, PrimaryColumn } from "typeorm";
+import { Snowflake } from "../util/Snowflake";
+import "missing-native-js-functions";
+import { getDatabase } from "..";
+import { OrmUtils } from "@fosscord/util";
+
+export class BaseClassWithoutId extends BaseEntity {
+ private get construct(): any {
+ return this.constructor;
+ }
+
+ private get metadata() {
+ return getDatabase()?.getMetadata(this.construct);
+ }
+
+ assign(props: any) {
+ OrmUtils.mergeDeep(this, props);
+ return this;
+ }
+
+ toJSON(): any {
+ return Object.fromEntries(
+ this.metadata!.columns // @ts-ignore
+ .map((x) => [x.propertyName, this[x.propertyName]]) // @ts-ignore
+ .concat(this.metadata.relations.map((x) => [x.propertyName, this[x.propertyName]]))
+ );
+ }
+
+ static increment<T extends BaseClass>(conditions: FindOptionsWhere<T>, propertyPath: string, value: number | string) {
+ const repository = this.getRepository();
+ return repository.increment(conditions, propertyPath, value);
+ }
+
+ static decrement<T extends BaseClass>(conditions: FindOptionsWhere<T>, propertyPath: string, value: number | string) {
+ const repository = this.getRepository();
+ return repository.decrement(conditions, propertyPath, value);
+ }
+}
+
+export const PrimaryIdColumn = process.env.DATABASE?.startsWith("mongodb") ? ObjectIdColumn : PrimaryColumn;
+
+export class BaseClass extends BaseClassWithoutId {
+ @PrimaryIdColumn()
+ id: string;
+
+ @BeforeUpdate()
+ @BeforeInsert()
+ do_validate() {
+ if (!this.id) this.id = Snowflake.generate();
+ }
+}
diff --git a/util/src/entities/Categories.ts b/src/util/entities/Categories.ts
index 81fbc303..81fbc303 100644
--- a/util/src/entities/Categories.ts
+++ b/src/util/entities/Categories.ts
diff --git a/util/src/entities/Channel.ts b/src/util/entities/Channel.ts
index 10fa03ff..577b627e 100644
--- a/util/src/entities/Channel.ts
+++ b/src/util/entities/Channel.ts
@@ -58,7 +58,7 @@ export class Channel extends BaseClass {
recipients?: Recipient[];
@Column({ nullable: true })
- last_message_id: string;
+ last_message_id?: string;
@Column({ nullable: true })
@RelationId((channel: Channel) => channel.guild)
@@ -81,7 +81,7 @@ export class Channel extends BaseClass {
// for group DMs and owned custom channel types
@Column({ nullable: true })
@RelationId((channel: Channel) => channel.owner)
- owner_id: string;
+ owner_id?: string;
@JoinColumn({ name: "owner_id" })
@ManyToOne(() => User)
@@ -169,7 +169,7 @@ export class Channel extends BaseClass {
}
if (!opts?.skipNameChecks) {
- const guild = await Guild.findOneOrFail({ id: channel.guild_id });
+ const guild = await Guild.findOneOrFail({ where: { id: channel.guild_id } });
if (!guild.features.includes("ALLOW_INVALID_CHANNEL_NAMES") && channel.name) {
for (var character of InvisibleCharacters)
if (channel.name.includes(character))
@@ -202,7 +202,7 @@ export class Channel extends BaseClass {
case ChannelType.GUILD_NEWS:
case ChannelType.GUILD_VOICE:
if (channel.parent_id && !opts?.skipExistsCheck) {
- const exists = await Channel.findOneOrFail({ id: channel.parent_id });
+ const exists = await Channel.findOneOrFail({ where: { id: channel.parent_id } });
if (!exists) throw new HTTPError("Parent id channel doesn't exist", 400);
if (exists.guild_id !== channel.guild_id)
throw new HTTPError("The category channel needs to be in the guild");
@@ -230,7 +230,7 @@ export class Channel extends BaseClass {
};
await Promise.all([
- new Channel(channel).save(),
+ Channel.create(channel).save(),
!opts?.skipEventEmit
? emitEvent({
event: "CHANNEL_CREATE",
@@ -281,15 +281,15 @@ export class Channel extends BaseClass {
if (channel == null) {
name = trimSpecial(name);
- channel = await new Channel({
+ channel = await Channel.create({
name,
type,
- owner_id: type === ChannelType.DM ? undefined : null, // 1:1 DMs are ownerless in fosscord-server
+ owner_id: undefined,
created_at: new Date(),
- last_message_id: null,
+ last_message_id: undefined,
recipients: channelRecipients.map(
(x) =>
- new Recipient({ user_id: x, closed: !(type === ChannelType.GROUP_DM || x === creator_user_id) })
+ Recipient.create({ user_id: x, closed: !(type === ChannelType.GROUP_DM || x === creator_user_id) })
),
nsfw: false,
}).save();
diff --git a/util/src/entities/ClientRelease.ts b/src/util/entities/ClientRelease.ts
index c5afd307..c5afd307 100644
--- a/util/src/entities/ClientRelease.ts
+++ b/src/util/entities/ClientRelease.ts
diff --git a/util/src/entities/Config.ts b/src/util/entities/Config.ts
index 9aabc1a8..9aabc1a8 100644
--- a/util/src/entities/Config.ts
+++ b/src/util/entities/Config.ts
diff --git a/util/src/entities/ConnectedAccount.ts b/src/util/entities/ConnectedAccount.ts
index 09ae30ab..09ae30ab 100644
--- a/util/src/entities/ConnectedAccount.ts
+++ b/src/util/entities/ConnectedAccount.ts
diff --git a/util/src/entities/Emoji.ts b/src/util/entities/Emoji.ts
index a3615b7d..a3615b7d 100644
--- a/util/src/entities/Emoji.ts
+++ b/src/util/entities/Emoji.ts
diff --git a/util/src/entities/Encryption.ts b/src/util/entities/Encryption.ts
index 3b82ff84..b597b90a 100644
--- a/util/src/entities/Encryption.ts
+++ b/src/util/entities/Encryption.ts
@@ -14,22 +14,22 @@ import { DmChannelDTO } from "../dtos";
@Entity("security_settings")
export class SecuritySettings extends BaseClass {
- @Column({nullable: true})
- guild_id: Snowflake;
+ @Column({ nullable: true })
+ guild_id: string;
- @Column({nullable: true})
- channel_id: Snowflake;
+ @Column({ nullable: true })
+ channel_id: string;
- @Column()
- encryption_permission_mask: BitField;
+ @Column()
+ encryption_permission_mask: number;
- @Column()
- allowed_algorithms: string[];
+ @Column({ type: "simple-array" })
+ allowed_algorithms: string[];
- @Column()
- current_algorithm: string;
+ @Column()
+ current_algorithm: string;
- @Column({nullable: true})
- used_since_message: Snowflake;
+ @Column({ nullable: true })
+ used_since_message: string;
}
diff --git a/util/src/entities/Guild.ts b/src/util/entities/Guild.ts
index 143cb542..2ce7c213 100644
--- a/util/src/entities/Guild.ts
+++ b/src/util/entities/Guild.ts
@@ -86,7 +86,7 @@ export class Guild extends BaseClass {
//TODO: https://discord.com/developers/docs/resources/guild#guild-object-guild-features
@Column({ nullable: true })
- primary_category_id: number;
+ primary_category_id?: string; // TODO: this was number?
@Column({ nullable: true })
icon?: string;
@@ -285,7 +285,7 @@ export class Guild extends BaseClass {
}) {
const guild_id = Snowflake.generate();
- const guild = await new Guild({
+ const guild = await Guild.create({
name: body.name || "Fosscord",
icon: await handleFile(`/icons/${guild_id}`, body.icon as string),
region: Config.get().regions.default,
@@ -294,7 +294,7 @@ export class Guild extends BaseClass {
default_message_notifications: 1, // defaults effect: setting the push default at mentions-only will save a lot
explicit_content_filter: 0,
features: Config.get().guild.defaultFeatures,
- primary_category_id: null,
+ primary_category_id: undefined,
id: guild_id,
max_members: 250000,
max_presences: 250000,
@@ -320,7 +320,7 @@ export class Guild extends BaseClass {
// we have to create the role _after_ the guild because else we would get a "SQLITE_CONSTRAINT: FOREIGN KEY constraint failed" error
// TODO: make the @everyone a pseudorole that is dynamically generated at runtime so we can save storage
- await new Role({
+ await Role.create({
id: guild_id,
guild_id: guild_id,
color: 0,
@@ -331,8 +331,8 @@ export class Guild extends BaseClass {
name: "@everyone",
permissions: String("2251804225"),
position: 0,
- icon: null,
- unicode_emoji: null
+ icon: undefined,
+ unicode_emoji: undefined
}).save();
if (!body.channels || !body.channels.length) body.channels = [{ id: "01", type: 0, name: "general", nsfw: false }];
diff --git a/util/src/entities/Invite.ts b/src/util/entities/Invite.ts
index 6ac64ddc..4f36f247 100644
--- a/util/src/entities/Invite.ts
+++ b/src/util/entities/Invite.ts
@@ -52,7 +52,7 @@ export class Invite extends BaseClassWithoutId {
@Column({ nullable: true })
@RelationId((invite: Invite) => invite.inviter)
- inviter_id: string;
+ inviter_id?: string;
@JoinColumn({ name: "inviter_id" })
@ManyToOne(() => User)
@@ -75,7 +75,7 @@ export class Invite extends BaseClassWithoutId {
vanity_url?: boolean;
static async joinGuild(user_id: string, code: string) {
- const invite = await Invite.findOneOrFail({ code });
+ const invite = await Invite.findOneOrFail({ where: { code } });
if (invite.uses++ >= invite.max_uses && invite.max_uses !== 0) await Invite.delete({ code });
else await invite.save();
diff --git a/util/src/entities/Member.ts b/src/util/entities/Member.ts
index 03698453..d7bcefea 100644
--- a/util/src/entities/Member.ts
+++ b/src/util/entities/Member.ts
@@ -1,6 +1,8 @@
import { PublicUser, User } from "./User";
import { Message } from "./Message";
import {
+ BeforeInsert,
+ BeforeUpdate,
Column,
Entity,
Index,
@@ -73,17 +75,6 @@ export class Member extends BaseClassWithoutId {
@Column({ nullable: true })
nick?: string;
- setNick(val: string) {
-
- if (val) {
- val = val.split("\n").join("");
- val = val.split("\t").join("");
- if (BannedWords.find(val)) throw FieldErrors({ nick: { message: "Bad nickname", code: "INVALID_NICKNAME" } });
- }
-
- this.nick = val;
- }
-
@JoinTable({
name: "member_roles",
joinColumn: { name: "index", referencedColumnName: "index" },
@@ -129,8 +120,18 @@ export class Member extends BaseClassWithoutId {
// @Column({ type: "simple-json" })
// read_state: ReadState;
+ @BeforeUpdate()
+ @BeforeInsert()
+ validate() {
+ if (this.nick) {
+ this.nick = this.nick.split("\n").join("");
+ this.nick = this.nick.split("\t").join("");
+ if (BannedWords.find(this.nick)) throw FieldErrors({ nick: { message: "Bad nickname", code: "INVALID_NICKNAME" } });
+ }
+ }
+
static async IsInGuildOrFail(user_id: string, guild_id: string) {
- if (await Member.count({ id: user_id, guild: { id: guild_id } })) return true;
+ if (await Member.count({ where: { id: user_id, guild: { id: guild_id } } })) return true;
throw new HTTPError("You are not member of this guild", 403);
}
@@ -168,11 +169,12 @@ export class Member extends BaseClassWithoutId {
Member.findOneOrFail({
where: { id: user_id, guild_id },
relations: ["user", "roles"], // we don't want to load the role objects just the ids
- select: ["index", "roles.id"],
+ //@ts-ignore
+ select: ["index", "roles.id"], // TODO fix type
}),
Role.findOneOrFail({ where: { id: role_id, guild_id }, select: ["id"] }),
]);
- member.roles.push(new Role({ id: role_id }));
+ member.roles.push(Role.create({ id: role_id }));
await Promise.all([
member.save(),
@@ -194,9 +196,10 @@ export class Member extends BaseClassWithoutId {
Member.findOneOrFail({
where: { id: user_id, guild_id },
relations: ["user", "roles"], // we don't want to load the role objects just the ids
- select: ["roles.id", "index"],
+ //@ts-ignore
+ select: ["roles.id", "index"], // TODO: fix type
}),
- await Role.findOneOrFail({ id: role_id, guild_id }),
+ await Role.findOneOrFail({ where: { id: role_id, guild_id } }),
]);
member.roles = member.roles.filter((x) => x.id == role_id);
@@ -246,7 +249,7 @@ export class Member extends BaseClassWithoutId {
throw DiscordApiErrors.USER_BANNED;
}
const { maxGuilds } = Config.get().limits.user;
- const guild_count = await Member.count({ id: user_id });
+ const guild_count = await Member.count({ where: { id: user_id } });
if (guild_count >= maxGuilds) {
throw new HTTPError(`You are at the ${maxGuilds} server limit.`, 403);
}
@@ -258,7 +261,7 @@ export class Member extends BaseClassWithoutId {
relations: [...PublicGuildRelations, "system_channel"],
});
- if (await Member.count({ id: user.id, guild: { id: guild_id } }))
+ if (await Member.count({ where: { id: user.id, guild: { id: guild_id } } }))
throw new HTTPError("You are already a member of this guild", 400);
const member = {
@@ -274,12 +277,18 @@ export class Member extends BaseClassWithoutId {
};
await Promise.all([
- new Member({
+ Member.create({
...member,
- roles: [new Role({ id: guild_id })],
+ roles: [Role.create({ id: guild_id })],
// read_state: {},
settings: {
- channel_overrides: [],
+ guild_id: null,
+ mute_config: null,
+ mute_scheduled_events: false,
+ flags: 0,
+ hide_muted_channels: false,
+ notify_highlights: 0,
+ channel_overrides: {},
message_notifications: 0,
mobile_push: true,
muted: false,
@@ -318,13 +327,12 @@ export class Member extends BaseClassWithoutId {
if (guild.system_channel_id) {
// send welcome message
- const message = new Message({
+ const message = Message.create({
type: 7,
guild_id: guild.id,
channel_id: guild.system_channel_id,
author: user,
timestamp: new Date(),
-
reactions: [],
attachments: [],
embeds: [],
@@ -385,7 +393,7 @@ export const DefaultUserGuildSettings: UserGuildSettings = {
suppress_roles: false,
version: 453, // ?
guild_id: null,
-}
+};
export interface MuteConfig {
end_time: number;
diff --git a/util/src/entities/Message.ts b/src/util/entities/Message.ts
index 6ea5c4aa..3a3dd5e4 100644
--- a/util/src/entities/Message.ts
+++ b/src/util/entities/Message.ts
@@ -5,6 +5,8 @@ import { Channel } from "./Channel";
import { InteractionType } from "../interfaces/Interaction";
import { Application } from "./Application";
import {
+ BeforeInsert,
+ BeforeUpdate,
Column,
CreateDateColumn,
Entity,
@@ -23,6 +25,7 @@ import { Sticker } from "./Sticker";
import { Attachment } from "./Attachment";
import { BannedWords } from "../util";
import { HTTPError } from "lambert-server";
+import { ValidatorConstraint } from "class-validator";
export enum MessageType {
DEFAULT = 0,
@@ -58,7 +61,7 @@ export class Message extends BaseClass {
@Column({ nullable: true })
@RelationId((message: Message) => message.channel)
@Index()
- channel_id: string;
+ channel_id?: string;
@JoinColumn({ name: "channel_id" })
@ManyToOne(() => Channel, {
@@ -79,7 +82,7 @@ export class Message extends BaseClass {
@Column({ nullable: true })
@RelationId((message: Message) => message.author)
@Index()
- author_id: string;
+ author_id?: string;
@JoinColumn({ name: "author_id", referencedColumnName: "id" })
@ManyToOne(() => User, {
@@ -89,7 +92,7 @@ export class Message extends BaseClass {
@Column({ nullable: true })
@RelationId((message: Message) => message.member)
- member_id: string;
+ member_id?: string;
@JoinColumn({ name: "member_id", referencedColumnName: "id" })
@ManyToOne(() => User, {
@@ -99,7 +102,7 @@ export class Message extends BaseClass {
@Column({ nullable: true })
@RelationId((message: Message) => message.webhook)
- webhook_id: string;
+ webhook_id?: string;
@JoinColumn({ name: "webhook_id" })
@ManyToOne(() => Webhook)
@@ -107,7 +110,7 @@ export class Message extends BaseClass {
@Column({ nullable: true })
@RelationId((message: Message) => message.application)
- application_id: string;
+ application_id?: string;
@JoinColumn({ name: "application_id" })
@ManyToOne(() => Application)
@@ -116,17 +119,12 @@ export class Message extends BaseClass {
@Column({ nullable: true, type: process.env.PRODUCTION ? "longtext" : undefined })
content?: string;
- setContent(val: string) {
- if (val && BannedWords.find(val)) throw new HTTPError("Message was blocked by automatic moderation", 200000);
- this.content = val;
- }
-
@Column()
@CreateDateColumn()
timestamp: Date;
@Column({ nullable: true })
- edited_timestamp: Date;
+ edited_timestamp?: Date;
@Column({ nullable: true })
tts?: boolean;
@@ -179,6 +177,7 @@ export class Message extends BaseClass {
@Column({ nullable: true })
flags?: string;
+
@Column({ type: "simple-json", nullable: true })
message_reference?: {
message_id: string;
@@ -201,6 +200,14 @@ export class Message extends BaseClass {
@Column({ type: "simple-json", nullable: true })
components?: MessageComponent[];
+
+ @BeforeUpdate()
+ @BeforeInsert()
+ validate() {
+ if (this.content) {
+ if (BannedWords.find(this.content)) throw new HTTPError("Message was blocked by automatic moderation", 200000);
+ }
+ }
}
export interface MessageComponent {
diff --git a/util/src/entities/Migration.ts b/src/util/entities/Migration.ts
index 3f39ae72..3f39ae72 100644
--- a/util/src/entities/Migration.ts
+++ b/src/util/entities/Migration.ts
diff --git a/util/src/entities/Note.ts b/src/util/entities/Note.ts
index 36017c5e..36017c5e 100644
--- a/util/src/entities/Note.ts
+++ b/src/util/entities/Note.ts
diff --git a/util/src/entities/RateLimit.ts b/src/util/entities/RateLimit.ts
index f5916f6b..f5916f6b 100644
--- a/util/src/entities/RateLimit.ts
+++ b/src/util/entities/RateLimit.ts
diff --git a/util/src/entities/ReadState.ts b/src/util/entities/ReadState.ts
index b915573b..b915573b 100644
--- a/util/src/entities/ReadState.ts
+++ b/src/util/entities/ReadState.ts
diff --git a/util/src/entities/Recipient.ts b/src/util/entities/Recipient.ts
index a945f938..a945f938 100644
--- a/util/src/entities/Recipient.ts
+++ b/src/util/entities/Recipient.ts
diff --git a/util/src/entities/Relationship.ts b/src/util/entities/Relationship.ts
index c3592c76..c3592c76 100644
--- a/util/src/entities/Relationship.ts
+++ b/src/util/entities/Relationship.ts
diff --git a/util/src/entities/Role.ts b/src/util/entities/Role.ts
index 4b721b5b..d87b835f 100644
--- a/util/src/entities/Role.ts
+++ b/src/util/entities/Role.ts
@@ -37,10 +37,10 @@ export class Role extends BaseClass {
position: number;
@Column({ nullable: true })
- icon: string;
+ icon?: string;
@Column({ nullable: true })
- unicode_emoji: string;
+ unicode_emoji?: string;
@Column({ type: "simple-json", nullable: true })
tags?: {
diff --git a/util/src/entities/Session.ts b/src/util/entities/Session.ts
index 969efa89..969efa89 100644
--- a/util/src/entities/Session.ts
+++ b/src/util/entities/Session.ts
diff --git a/util/src/entities/Sticker.ts b/src/util/entities/Sticker.ts
index 37bc6fbe..37bc6fbe 100644
--- a/util/src/entities/Sticker.ts
+++ b/src/util/entities/Sticker.ts
diff --git a/util/src/entities/StickerPack.ts b/src/util/entities/StickerPack.ts
index ec8c69a2..ec8c69a2 100644
--- a/util/src/entities/StickerPack.ts
+++ b/src/util/entities/StickerPack.ts
diff --git a/util/src/entities/Team.ts b/src/util/entities/Team.ts
index 22140b7f..22140b7f 100644
--- a/util/src/entities/Team.ts
+++ b/src/util/entities/Team.ts
diff --git a/util/src/entities/TeamMember.ts b/src/util/entities/TeamMember.ts
index b726e1e8..b726e1e8 100644
--- a/util/src/entities/TeamMember.ts
+++ b/src/util/entities/TeamMember.ts
diff --git a/util/src/entities/Template.ts b/src/util/entities/Template.ts
index 1d952283..1d952283 100644
--- a/util/src/entities/Template.ts
+++ b/src/util/entities/Template.ts
diff --git a/util/src/entities/User.ts b/src/util/entities/User.ts
index 35aeea52..84a8a674 100644
--- a/util/src/entities/User.ts
+++ b/src/util/entities/User.ts
@@ -1,4 +1,4 @@
-import { Column, Entity, FindOneOptions, JoinColumn, OneToMany } from "typeorm";
+import { BeforeInsert, BeforeUpdate, Column, Entity, FindOneOptions, JoinColumn, OneToMany } from "typeorm";
import { BaseClass } from "./BaseClass";
import { BitField } from "../util/BitField";
import { Relationship } from "./Relationship";
@@ -59,23 +59,9 @@ export class User extends BaseClass {
@Column()
username: string; // username max length 32, min 2 (should be configurable)
- setUsername(val: string) {
- if (BannedWords.find(val)) throw FieldErrors({ username: { message: "Bad username", code: "INVALID_USERNAME" } });
- this.username = val;
- }
-
@Column()
discriminator: string; // opaque string: 4 digits on discord.com
- setDiscriminator(val: string) {
- const number = Number(val);
- if (val.length > 4) throw new Error("invalid discriminator");
- if (isNaN(number)) throw new Error("invalid discriminator");
- if (number <= 0 || number >= 10000) throw new Error("discriminator must be between 1 and 9999");
- val = Number(val).toString();
- this.discriminator = val.toString().padStart(4, "0");
- }
-
@Column({ nullable: true })
avatar?: string; // hash of the user avatar
@@ -139,13 +125,6 @@ export class User extends BaseClass {
@Column({ nullable: true, select: false })
email?: string; // email of the user
- setEmail(val?: string) {
- val = adjustEmail(val);
- if (!val) throw FieldErrors({ email: { message: "Invalid email", code: "EMAIL_INVALID" } });
- if (!val.match(/([a-z\d.-]{3,})@([a-z\d.-]+).([a-z]{2,})/g)) throw FieldErrors({ email: { message: "Invalid email", code: "EMAIL_INVALID" } });
- this.email = val;
- }
-
@Column()
flags: string; // UserFlags
@@ -194,6 +173,22 @@ export class User extends BaseClass {
@Column({ type: "simple-json", select: false })
extended_settings: string;
+ @BeforeUpdate()
+ @BeforeInsert()
+ validate() {
+ this.email = adjustEmail(this.email);
+ if (!this.email) throw FieldErrors({ email: { message: "Invalid email", code: "EMAIL_INVALID" } });
+ if (!this.email.match(/([a-z\d.-]{3,})@([a-z\d.-]+).([a-z]{2,})/g)) throw FieldErrors({ email: { message: "Invalid email", code: "EMAIL_INVALID" } });
+
+ const discrim = Number(this.discriminator);
+ if (this.discriminator.length > 4) throw FieldErrors({ email: { message: "Discriminator cannot be more than 4 digits.", code: "DISCRIMINATOR_INVALID" } });
+ if (isNaN(discrim)) throw FieldErrors({ email: { message: "Discriminator must be a number.", code: "DISCRIMINATOR_INVALID" } });
+ if (discrim <= 0 || discrim >= 10000) throw FieldErrors({ email: { message: "Discriminator must be a number.", code: "DISCRIMINATOR_INVALID" } });
+ this.discriminator = discrim.toString().padStart(4, "0");
+
+ if (BannedWords.find(this.username)) throw FieldErrors({ username: { message: "Bad username", code: "INVALID_USERNAME" } });
+ }
+
toPublicUser() {
const user: any = {};
PublicUserProjection.forEach((x) => {
@@ -203,13 +198,12 @@ export class User extends BaseClass {
}
static async getPublicUser(user_id: string, opts?: FindOneOptions<User>) {
- return await User.findOneOrFail(
- { id: user_id },
- {
- ...opts,
- select: [...PublicUserProjection, ...(opts?.select || [])],
- }
- );
+ return await User.findOneOrFail({
+ where: { id: user_id },
+ ...opts,
+ //@ts-ignore
+ select: [...PublicUserProjection, ...(opts?.select || [])], // TODO: fix
+ });
}
private static async generateDiscriminator(username: string): Promise<string | undefined> {
@@ -273,7 +267,7 @@ export class User extends BaseClass {
// if nsfw_allowed is null/undefined it'll require date_of_birth to set it to true/false
const language = req.language === "en" ? "en-US" : req.language || "en-US";
- const user = new User({
+ const user = User.create({
created_at: new Date(),
username: username,
discriminator,
@@ -293,7 +287,7 @@ export class User extends BaseClass {
email: email,
rights: Config.get().security.defaultRights,
nsfw_allowed: true, // TODO: depending on age
- public_flags: "0",
+ public_flags: 0,
flags: "0", // TODO: generate
data: {
hash: password,
@@ -302,9 +296,8 @@ export class User extends BaseClass {
settings: { ...defaultSettings, locale: language },
purchased_flags: 5, // TODO: idk what the values for this are
premium_usage_flags: 2, // TODO: idk what the values for this are
- extended_settings: {},
+ extended_settings: "", // TODO: was {}
fingerprints: [],
- notes: {},
});
await user.save();
diff --git a/util/src/entities/VoiceState.ts b/src/util/entities/VoiceState.ts
index 75748a01..75748a01 100644
--- a/util/src/entities/VoiceState.ts
+++ b/src/util/entities/VoiceState.ts
diff --git a/util/src/entities/Webhook.ts b/src/util/entities/Webhook.ts
index 89538417..89538417 100644
--- a/util/src/entities/Webhook.ts
+++ b/src/util/entities/Webhook.ts
diff --git a/util/src/entities/index.ts b/src/util/entities/index.ts
index 49793810..49793810 100644
--- a/util/src/entities/index.ts
+++ b/src/util/entities/index.ts
diff --git a/src/util/imports/OrmUtils.ts b/src/util/imports/OrmUtils.ts
new file mode 100644
index 00000000..68a1932c
--- /dev/null
+++ b/src/util/imports/OrmUtils.ts
@@ -0,0 +1,96 @@
+//source: https://github.com/typeorm/typeorm/blob/master/src/util/OrmUtils.ts
+export class OrmUtils {
+ // Checks if it's an object made by Object.create(null), {} or new Object()
+ private static isPlainObject(item: any) {
+ if (item === null || item === undefined) {
+ return false;
+ }
+
+ return !item.constructor || item.constructor === Object;
+ }
+
+ private static mergeArrayKey(target: any, key: number, value: any, memo: Map<any, any>) {
+ // Have we seen this before? Prevent infinite recursion.
+ if (memo.has(value)) {
+ target[key] = memo.get(value);
+ return;
+ }
+
+ if (value instanceof Promise) {
+ // Skip promises entirely.
+ // This is a hold-over from the old code & is because we don't want to pull in
+ // the lazy fields. Ideally we'd remove these promises via another function first
+ // but for now we have to do it here.
+ return;
+ }
+
+ if (!this.isPlainObject(value) && !Array.isArray(value)) {
+ target[key] = value;
+ return;
+ }
+
+ if (!target[key]) {
+ target[key] = Array.isArray(value) ? [] : {};
+ }
+
+ memo.set(value, target[key]);
+ this.merge(target[key], value, memo);
+ memo.delete(value);
+ }
+
+ private static mergeObjectKey(target: any, key: string, value: any, memo: Map<any, any>) {
+ // Have we seen this before? Prevent infinite recursion.
+ if (memo.has(value)) {
+ Object.assign(target, { [key]: memo.get(value) });
+ return;
+ }
+
+ if (value instanceof Promise) {
+ // Skip promises entirely.
+ // This is a hold-over from the old code & is because we don't want to pull in
+ // the lazy fields. Ideally we'd remove these promises via another function first
+ // but for now we have to do it here.
+ return;
+ }
+
+ if (!this.isPlainObject(value) && !Array.isArray(value)) {
+ Object.assign(target, { [key]: value });
+ return;
+ }
+
+ if (!target[key]) {
+ Object.assign(target, { [key]: value });
+ }
+
+ memo.set(value, target[key]);
+ this.merge(target[key], value, memo);
+ memo.delete(value);
+ }
+
+ private static merge(target: any, source: any, memo: Map<any, any> = new Map()): any {
+ if (Array.isArray(target) && Array.isArray(source)) {
+ for (let key = 0; key < source.length; key++) {
+ this.mergeArrayKey(target, key, source[key], memo);
+ }
+ } else {
+ for (const key of Object.keys(source)) {
+ this.mergeObjectKey(target, key, source[key], memo);
+ }
+ }
+ }
+
+ /**
+ * Deep Object.assign.
+ */
+ static mergeDeep(target: any, ...sources: any[]): any {
+ if (!sources.length) {
+ return target;
+ }
+
+ for (const source of sources) {
+ OrmUtils.merge(target, source);
+ }
+
+ return target;
+ }
+}
\ No newline at end of file
diff --git a/src/util/imports/index.ts b/src/util/imports/index.ts
new file mode 100644
index 00000000..5d9bfb5f
--- /dev/null
+++ b/src/util/imports/index.ts
@@ -0,0 +1 @@
+export * from "./OrmUtils";
\ No newline at end of file
diff --git a/util/src/index.ts b/src/util/index.ts
index 52117302..385070a3 100644
--- a/util/src/index.ts
+++ b/src/util/index.ts
@@ -4,4 +4,5 @@ export * from "./util/index";
export * from "./interfaces/index";
export * from "./entities/index";
export * from "./dtos/index";
-export * from "./schemas";
\ No newline at end of file
+export * from "./schemas";
+export * from "./imports";
\ No newline at end of file
diff --git a/util/src/interfaces/Activity.ts b/src/util/interfaces/Activity.ts
index 9912e197..9912e197 100644
--- a/util/src/interfaces/Activity.ts
+++ b/src/util/interfaces/Activity.ts
diff --git a/util/src/interfaces/Event.ts b/src/util/interfaces/Event.ts
index 59f995db..59f995db 100644
--- a/util/src/interfaces/Event.ts
+++ b/src/util/interfaces/Event.ts
diff --git a/util/src/interfaces/Interaction.ts b/src/util/interfaces/Interaction.ts
index 5d3aae24..5d3aae24 100644
--- a/util/src/interfaces/Interaction.ts
+++ b/src/util/interfaces/Interaction.ts
diff --git a/util/src/interfaces/Presence.ts b/src/util/interfaces/Presence.ts
index 7663891a..7663891a 100644
--- a/util/src/interfaces/Presence.ts
+++ b/src/util/interfaces/Presence.ts
diff --git a/util/src/interfaces/Status.ts b/src/util/interfaces/Status.ts
index 5d2e1bba..5d2e1bba 100644
--- a/util/src/interfaces/Status.ts
+++ b/src/util/interfaces/Status.ts
diff --git a/util/src/interfaces/index.ts b/src/util/interfaces/index.ts
index ab7fa429..ab7fa429 100644
--- a/util/src/interfaces/index.ts
+++ b/src/util/interfaces/index.ts
diff --git a/util/src/migrations/1633864260873-EmojiRoles.ts b/src/util/migrations/1633864260873-EmojiRoles.ts
index f0d709f2..f0d709f2 100644
--- a/util/src/migrations/1633864260873-EmojiRoles.ts
+++ b/src/util/migrations/1633864260873-EmojiRoles.ts
diff --git a/util/src/migrations/1633864669243-EmojiUser.ts b/src/util/migrations/1633864669243-EmojiUser.ts
index 982405d7..982405d7 100644
--- a/util/src/migrations/1633864669243-EmojiUser.ts
+++ b/src/util/migrations/1633864669243-EmojiUser.ts
diff --git a/util/src/migrations/1633881705509-VanityInvite.ts b/src/util/migrations/1633881705509-VanityInvite.ts
index 45485310..45485310 100644
--- a/util/src/migrations/1633881705509-VanityInvite.ts
+++ b/src/util/migrations/1633881705509-VanityInvite.ts
diff --git a/util/src/migrations/1634308884591-Stickers.ts b/src/util/migrations/1634308884591-Stickers.ts
index fbc4649f..fbc4649f 100644
--- a/util/src/migrations/1634308884591-Stickers.ts
+++ b/src/util/migrations/1634308884591-Stickers.ts
diff --git a/util/src/migrations/1634424361103-Presence.ts b/src/util/migrations/1634424361103-Presence.ts
index 729955b8..729955b8 100644
--- a/util/src/migrations/1634424361103-Presence.ts
+++ b/src/util/migrations/1634424361103-Presence.ts
diff --git a/util/src/migrations/1634426540271-MigrationTimestamp.ts b/src/util/migrations/1634426540271-MigrationTimestamp.ts
index 3208b25b..3208b25b 100644
--- a/util/src/migrations/1634426540271-MigrationTimestamp.ts
+++ b/src/util/migrations/1634426540271-MigrationTimestamp.ts
diff --git a/util/src/migrations/1648643945733-ReleaseTypo.ts b/src/util/migrations/1648643945733-ReleaseTypo.ts
index 944b9dd9..944b9dd9 100644
--- a/util/src/migrations/1648643945733-ReleaseTypo.ts
+++ b/src/util/migrations/1648643945733-ReleaseTypo.ts
diff --git a/util/src/migrations/1660678870706-opencordFixes.ts b/src/util/migrations/1660678870706-opencordFixes.ts
index 1f10c212..1f10c212 100644
--- a/util/src/migrations/1660678870706-opencordFixes.ts
+++ b/src/util/migrations/1660678870706-opencordFixes.ts
diff --git a/util/src/migrations/1660689892073-mobileFixes2.ts b/src/util/migrations/1660689892073-mobileFixes2.ts
index bd28694e..bd28694e 100644
--- a/util/src/migrations/1660689892073-mobileFixes2.ts
+++ b/src/util/migrations/1660689892073-mobileFixes2.ts
diff --git a/util/src/schemas/Validator.ts b/src/util/schemas/Validator.ts
index e5f12ac5..b71bf6a1 100644
--- a/util/src/schemas/Validator.ts
+++ b/src/util/schemas/Validator.ts
@@ -3,7 +3,7 @@ import addFormats from "ajv-formats";
import fs from "fs";
import path from "path";
-const SchemaPath = path.join(__dirname, "..", "..", "..", "api", "assets", "schemas.json");
+const SchemaPath = path.join(__dirname, "..", "..", "..", "assets", "schemas.json");
const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
export const ajv = new Ajv({
diff --git a/util/src/schemas/index.ts b/src/util/schemas/index.ts
index 662152dc..662152dc 100644
--- a/util/src/schemas/index.ts
+++ b/src/util/schemas/index.ts
diff --git a/util/src/schemas/voice.ts b/src/util/schemas/voice.ts
index 61c12f92..61c12f92 100644
--- a/util/src/schemas/voice.ts
+++ b/src/util/schemas/voice.ts
diff --git a/util/src/util/ApiError.ts b/src/util/util/ApiError.ts
index f1a9b4f6..f1a9b4f6 100644
--- a/util/src/util/ApiError.ts
+++ b/src/util/util/ApiError.ts
diff --git a/util/src/util/Array.ts b/src/util/util/Array.ts
index 5a45d1b5..5a45d1b5 100644
--- a/util/src/util/Array.ts
+++ b/src/util/util/Array.ts
diff --git a/util/src/util/AutoUpdate.ts b/src/util/util/AutoUpdate.ts
index 531bd8b7..fd65ecf5 100644
--- a/util/src/util/AutoUpdate.ts
+++ b/src/util/util/AutoUpdate.ts
@@ -76,7 +76,7 @@ async function getLatestVersion(url: string) {
try {
const agent = new ProxyAgent();
const response = await fetch(url, { agent });
- const content = await response.json();
+ const content = await response.json() as any; // TODO: types
return content.version;
} catch (error) {
throw new Error("[Auto update] check failed for " + url);
diff --git a/util/src/util/BannedWords.ts b/src/util/util/BannedWords.ts
index 891a5980..891a5980 100644
--- a/util/src/util/BannedWords.ts
+++ b/src/util/util/BannedWords.ts
diff --git a/util/src/util/BitField.ts b/src/util/util/BitField.ts
index fb887e05..fb887e05 100644
--- a/util/src/util/BitField.ts
+++ b/src/util/util/BitField.ts
diff --git a/util/src/util/Categories.ts b/src/util/util/Categories.ts
index a3c69da7..a3c69da7 100644
--- a/util/src/util/Categories.ts
+++ b/src/util/util/Categories.ts
diff --git a/util/src/util/Config.ts b/src/util/util/Config.ts
index 31b8d97c..31b8d97c 100644
--- a/util/src/util/Config.ts
+++ b/src/util/util/Config.ts
diff --git a/util/src/util/Constants.ts b/src/util/util/Constants.ts
index 81a7165d..81a7165d 100644
--- a/util/src/util/Constants.ts
+++ b/src/util/util/Constants.ts
diff --git a/src/util/util/Database.ts b/src/util/util/Database.ts
new file mode 100644
index 00000000..ddbea57d
--- /dev/null
+++ b/src/util/util/Database.ts
@@ -0,0 +1,96 @@
+import path from "path";
+import "reflect-metadata";
+import { DataSource } from "typeorm";
+import * as Models from "../entities";
+import { Migration } from "../entities/Migration";
+import { yellow, green, red } from "picocolors";
+
+// UUID extension option is only supported with postgres
+// We want to generate all id's with Snowflakes that's why we have our own BaseEntity class
+
+var dbConnection: DataSource | undefined;
+let dbConnectionString = process.env.DATABASE || path.join(process.cwd(), "database.db");
+
+export function getDatabase(): DataSource | null {
+ // if (!dbConnection) throw new Error("Tried to get database before it was initialised");
+ if (!dbConnection) return null;
+ return dbConnection;
+}
+
+export async function initDatabase(): Promise<DataSource> {
+ if (dbConnection) return dbConnection;
+
+ const type = dbConnectionString.includes("://") ? dbConnectionString.split(":")[0]?.replace("+srv", "") : "sqlite";
+ const isSqlite = type.includes("sqlite");
+
+ console.log(`[Database] ${yellow(`connecting to ${type} db`)}`);
+ if (isSqlite) {
+ console.log(`[Database] ${red(`You are running sqlite! Please keep in mind that we recommend setting up a dedicated database!`)}`);
+ }
+
+ const dataSource = new DataSource({
+ //@ts-ignore
+ type,
+ charset: 'utf8mb4',
+ url: isSqlite ? undefined : dbConnectionString,
+ database: isSqlite ? dbConnectionString : undefined,
+ entities: ["dist/util/entities/*.js"],
+ synchronize: type !== "mongodb",
+ logging: false,
+ bigNumberStrings: false,
+ supportBigNumbers: true,
+ name: "default",
+ // migrations: [path.join(__dirname, "..", "migrations", "*.js")],
+ });
+
+ dbConnection = await dataSource.initialize();
+
+ // // @ts-ignore
+ // promise = createConnection({
+ // type,
+ // charset: 'utf8mb4',
+ // url: isSqlite ? undefined : dbConnectionString,
+ // database: isSqlite ? dbConnectionString : undefined,
+ // // @ts-ignore
+ // entities: Object.values(Models).filter((x) => x?.constructor?.name !== "Object" && x?.name),
+ // synchronize: type !== "mongodb",
+ // logging: false,
+ // // cache: { // cache is used only by query builder and entity manager
+ // // duration: 1000 * 30,
+ // // type: "redis",
+ // // options: {
+ // // host: "localhost",
+ // // port: 6379,
+ // // },
+ // // },
+ // bigNumberStrings: false,
+ // supportBigNumbers: true,
+ // name: "default",
+ // migrations: [path.join(__dirname, "..", "migrations", "*.js")],
+ // });
+
+ // // run migrations, and if it is a new fresh database, set it to the last migration
+ // if (dbConnection.migrations.length) {
+ // if (!(await Migration.findOne({ }))) {
+ // let i = 0;
+
+ // await Migration.insert(
+ // dbConnection.migrations.map((x) => ({
+ // id: i++,
+ // name: x.name,
+ // timestamp: Date.now(),
+ // }))
+ // );
+ // }
+ // }
+ await dbConnection.runMigrations();
+ console.log(`[Database] ${green("connected")}`);
+
+ return dbConnection;
+}
+
+export { dbConnection };
+
+export function closeDatabase() {
+ dbConnection?.destroy();
+}
diff --git a/util/src/util/Email.ts b/src/util/util/Email.ts
index 6885da33..6885da33 100644
--- a/util/src/util/Email.ts
+++ b/src/util/util/Email.ts
diff --git a/util/src/util/Event.ts b/src/util/util/Event.ts
index 20a638a0..20a638a0 100644
--- a/util/src/util/Event.ts
+++ b/src/util/util/Event.ts
diff --git a/util/src/util/FieldError.ts b/src/util/util/FieldError.ts
index 406b33e8..406b33e8 100644
--- a/util/src/util/FieldError.ts
+++ b/src/util/util/FieldError.ts
diff --git a/util/src/util/Intents.ts b/src/util/util/Intents.ts
index 1e840b76..1e840b76 100644
--- a/util/src/util/Intents.ts
+++ b/src/util/util/Intents.ts
diff --git a/util/src/util/InvisibleCharacters.ts b/src/util/util/InvisibleCharacters.ts
index a48cfab0..a48cfab0 100644
--- a/util/src/util/InvisibleCharacters.ts
+++ b/src/util/util/InvisibleCharacters.ts
diff --git a/util/src/util/MessageFlags.ts b/src/util/util/MessageFlags.ts
index b59295c4..b59295c4 100644
--- a/util/src/util/MessageFlags.ts
+++ b/src/util/util/MessageFlags.ts
diff --git a/util/src/util/Permissions.ts b/src/util/util/Permissions.ts
index e5459ab5..e5459ab5 100644
--- a/util/src/util/Permissions.ts
+++ b/src/util/util/Permissions.ts
diff --git a/util/src/util/RabbitMQ.ts b/src/util/util/RabbitMQ.ts
index 0f5eb6aa..0f5eb6aa 100644
--- a/util/src/util/RabbitMQ.ts
+++ b/src/util/util/RabbitMQ.ts
diff --git a/util/src/util/Regex.ts b/src/util/util/Regex.ts
index 83fc9fe8..83fc9fe8 100644
--- a/util/src/util/Regex.ts
+++ b/src/util/util/Regex.ts
diff --git a/util/src/util/Rights.ts b/src/util/util/Rights.ts
index b28c75b7..b28c75b7 100644
--- a/util/src/util/Rights.ts
+++ b/src/util/util/Rights.ts
diff --git a/util/src/util/Snowflake.ts b/src/util/util/Snowflake.ts
index 134d526e..134d526e 100644
--- a/util/src/util/Snowflake.ts
+++ b/src/util/util/Snowflake.ts
diff --git a/util/src/util/String.ts b/src/util/util/String.ts
index 55f11e8d..55f11e8d 100644
--- a/util/src/util/String.ts
+++ b/src/util/util/String.ts
diff --git a/util/src/util/Token.ts b/src/util/util/Token.ts
index 500ace45..5ba3e1ec 100644
--- a/util/src/util/Token.ts
+++ b/src/util/util/Token.ts
@@ -11,14 +11,14 @@ export function checkToken(token: string, jwtSecret: string): Promise<any> {
in fosscord, even with instances that have bot distinction; we won't enforce "Bot" prefix,
as we don't really have separate pathways for bots
**/
-
+
jwt.verify(token, jwtSecret, JWTOptions, async (err, decoded: any) => {
if (err || !decoded) return rej("Invalid Token");
- const user = await User.findOne(
- { id: decoded.id },
- { select: ["data", "bot", "disabled", "deleted", "rights"] }
- );
+ const user = await User.findOne({
+ where: { id: decoded.id },
+ select: ["data", "bot", "disabled", "deleted", "rights"]
+ });
if (!user) return rej("Invalid Token");
// we need to round it to seconds as it saved as seconds in jwt iat and valid_tokens_since is stored in milliseconds
if (decoded.iat * 1000 < new Date(user.data.valid_tokens_since).setSeconds(0, 0))
diff --git a/util/src/util/TraverseDirectory.ts b/src/util/util/TraverseDirectory.ts
index 3d0d6279..3d0d6279 100644
--- a/util/src/util/TraverseDirectory.ts
+++ b/src/util/util/TraverseDirectory.ts
diff --git a/util/src/util/cdn.ts b/src/util/util/cdn.ts
index ea950cd1..812a4e1d 100644
--- a/util/src/util/cdn.ts
+++ b/src/util/util/cdn.ts
@@ -1,10 +1,10 @@
import FormData from "form-data";
import { HTTPError } from "lambert-server";
import fetch from "node-fetch";
+import { Attachment } from "../entities";
import { Config } from "./Config";
-import multer from "multer";
-export async function uploadFile(path: string, file?: Express.Multer.File) {
+export async function uploadFile(path: string, file?: Express.Multer.File): Promise<Attachment> {
if (!file?.buffer) throw new HTTPError("Missing file in body");
const form = new FormData();
@@ -21,7 +21,7 @@ export async function uploadFile(path: string, file?: Express.Multer.File) {
method: "POST",
body: form,
});
- const result = await response.json();
+ const result = await response.json() as Attachment;
if (response.status !== 200) throw result;
return result;
diff --git a/util/src/util/index.ts b/src/util/util/index.ts
index b2bd6489..b2bd6489 100644
--- a/util/src/util/index.ts
+++ b/src/util/util/index.ts
diff --git a/webrtc/.DS_Store b/src/webrtc/.DS_Store
index bfb0a416..bfb0a416 100644
--- a/webrtc/.DS_Store
+++ b/src/webrtc/.DS_Store
Binary files differdiff --git a/webrtc/src/Server.ts b/src/webrtc/Server.ts
index 32b795ea..32b795ea 100644
--- a/webrtc/src/Server.ts
+++ b/src/webrtc/Server.ts
diff --git a/webrtc/src/events/Close.ts b/src/webrtc/events/Close.ts
index 1c203653..1c203653 100644
--- a/webrtc/src/events/Close.ts
+++ b/src/webrtc/events/Close.ts
diff --git a/webrtc/src/events/Connection.ts b/src/webrtc/events/Connection.ts
index bf228d64..bf228d64 100644
--- a/webrtc/src/events/Connection.ts
+++ b/src/webrtc/events/Connection.ts
diff --git a/webrtc/src/events/Message.ts b/src/webrtc/events/Message.ts
index 8f75a815..8f75a815 100644
--- a/webrtc/src/events/Message.ts
+++ b/src/webrtc/events/Message.ts
diff --git a/webrtc/src/index.ts b/src/webrtc/index.ts
index 7cecc9b6..7cecc9b6 100644
--- a/webrtc/src/index.ts
+++ b/src/webrtc/index.ts
diff --git a/webrtc/src/opcodes/BackendVersion.ts b/src/webrtc/opcodes/BackendVersion.ts
index b4b61c7d..b4b61c7d 100644
--- a/webrtc/src/opcodes/BackendVersion.ts
+++ b/src/webrtc/opcodes/BackendVersion.ts
diff --git a/webrtc/src/opcodes/Heartbeat.ts b/src/webrtc/opcodes/Heartbeat.ts
index 1b6c5bcd..1b6c5bcd 100644
--- a/webrtc/src/opcodes/Heartbeat.ts
+++ b/src/webrtc/opcodes/Heartbeat.ts
diff --git a/webrtc/src/opcodes/Identify.ts b/src/webrtc/opcodes/Identify.ts
index 19a575ab..19a575ab 100644
--- a/webrtc/src/opcodes/Identify.ts
+++ b/src/webrtc/opcodes/Identify.ts
diff --git a/webrtc/src/opcodes/SelectProtocol.ts b/src/webrtc/opcodes/SelectProtocol.ts
index a3579b34..a3579b34 100644
--- a/webrtc/src/opcodes/SelectProtocol.ts
+++ b/src/webrtc/opcodes/SelectProtocol.ts
diff --git a/webrtc/src/opcodes/Speaking.ts b/src/webrtc/opcodes/Speaking.ts
index e2227040..e2227040 100644
--- a/webrtc/src/opcodes/Speaking.ts
+++ b/src/webrtc/opcodes/Speaking.ts
diff --git a/webrtc/src/opcodes/Video.ts b/src/webrtc/opcodes/Video.ts
index ff20d5a9..ff20d5a9 100644
--- a/webrtc/src/opcodes/Video.ts
+++ b/src/webrtc/opcodes/Video.ts
diff --git a/webrtc/src/opcodes/index.ts b/src/webrtc/opcodes/index.ts
index 8c664cce..8c664cce 100644
--- a/webrtc/src/opcodes/index.ts
+++ b/src/webrtc/opcodes/index.ts
diff --git a/webrtc/src/opcodes/sdp.json b/src/webrtc/opcodes/sdp.json
index 4867b9c7..4867b9c7 100644
--- a/webrtc/src/opcodes/sdp.json
+++ b/src/webrtc/opcodes/sdp.json
diff --git a/webrtc/src/start.ts b/src/webrtc/start.ts
index 9a5f38ee..9a5f38ee 100644
--- a/webrtc/src/start.ts
+++ b/src/webrtc/start.ts
diff --git a/webrtc/src/util/Constants.ts b/src/webrtc/util/Constants.ts
index 64d78e22..64d78e22 100644
--- a/webrtc/src/util/Constants.ts
+++ b/src/webrtc/util/Constants.ts
diff --git a/webrtc/src/util/MediaServer.ts b/src/webrtc/util/MediaServer.ts
index 93230c91..93230c91 100644
--- a/webrtc/src/util/MediaServer.ts
+++ b/src/webrtc/util/MediaServer.ts
diff --git a/webrtc/src/util/index.ts b/src/webrtc/util/index.ts
index 2e09bc48..2e09bc48 100644
--- a/webrtc/src/util/index.ts
+++ b/src/webrtc/util/index.ts
|