From c0fd1d1f2fe49efb26756f9c15d6bf31b9e80414 Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Mon, 5 Apr 2021 21:24:36 +0200 Subject: :bug: fix body parser --- src/util/instanceOf.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/util') diff --git a/src/util/instanceOf.ts b/src/util/instanceOf.ts index 4f30bd46..eb2894cd 100644 --- a/src/util/instanceOf.ts +++ b/src/util/instanceOf.ts @@ -114,8 +114,6 @@ export function instanceOf( } if (typeof type === "object") { - if (typeof value !== "object") throw new FieldError("BASE_TYPE_OBJECT", req.t("common:field.BASE_TYPE_OBJECT")); - if (Array.isArray(type)) { if (!Array.isArray(value)) throw new FieldError("BASE_TYPE_ARRAY", req.t("common:field.BASE_TYPE_ARRAY")); if (!type.length) return true; // type array didn't specify any type @@ -154,6 +152,8 @@ export function instanceOf( throw new FieldError("BASE_TYPE_CLASS", req.t("common:field.BASE_TYPE_CLASS", { type })); } + if (typeof value !== "object") throw new FieldError("BASE_TYPE_OBJECT", req.t("common:field.BASE_TYPE_OBJECT")); + const diff = Object.keys(value).missing( Object.keys(type).map((x) => (x.startsWith(OPTIONAL_PREFIX) ? x.slice(OPTIONAL_PREFIX.length) : x)) ); -- cgit 1.5.1 From 4f67c2c86e1a418c66ef5bab9712b2dc289d83fc Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Tue, 6 Apr 2021 04:05:46 +0200 Subject: :art: proper error message body parser --- src/util/instanceOf.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src/util') diff --git a/src/util/instanceOf.ts b/src/util/instanceOf.ts index eb2894cd..869f56d4 100644 --- a/src/util/instanceOf.ts +++ b/src/util/instanceOf.ts @@ -148,8 +148,11 @@ export function instanceOf( }) ); } - if (value instanceof type) return true; - throw new FieldError("BASE_TYPE_CLASS", req.t("common:field.BASE_TYPE_CLASS", { type })); + try { + if (value instanceof type) return true; + } catch (error) { + throw new FieldError("BASE_TYPE_CLASS", req.t("common:field.BASE_TYPE_CLASS", { type })); + } } if (typeof value !== "object") throw new FieldError("BASE_TYPE_OBJECT", req.t("common:field.BASE_TYPE_OBJECT")); -- cgit 1.5.1 From 5f3cea845d56ae49ab224df044eb13867b1afae4 Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Tue, 6 Apr 2021 04:06:07 +0200 Subject: :sparkles: test client --- assets/endpoints.json | 115 ++++++++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 4 +- src/Server.ts | 2 +- src/util/Member.ts | 2 - 4 files changed, 118 insertions(+), 5 deletions(-) create mode 100644 assets/endpoints.json (limited to 'src/util') diff --git a/assets/endpoints.json b/assets/endpoints.json new file mode 100644 index 00000000..8b0514ce --- /dev/null +++ b/assets/endpoints.json @@ -0,0 +1,115 @@ +{ + "USER_CHANNELS": "/users/@me/channels", + "USER_ACTIVITY_STATISTICS": "/users/@me/activities/statistics/applications", + "ACTIVITIES": "/activities", + "LOBBIES": "/lobbies", + "LOBBY_SEARCH": "/lobbies/search", + "NETWORKING_TOKEN": "/networking/token", + "USER_GAMES_NOTIFICATIONS": "/users/@me/settings/game-notifications", + "USER_GAMES_NOTIFICATIONS_OVERRIDES": "/users/@me/settings/game-notifications/overrides", + "UNVERIFIED_APPLICATIONS": "/unverified-applications", + "UNVERIFIED_APPLICATIONS_ICONS": "/unverified-applications/icons", + "BULK_ACK": "/read-states/ack-bulk", + "GUILDS": "/guilds", + "CHANNELS": "/channels", + "TUTORIAL_INDICATORS": "/tutorial/indicators", + "TUTORIAL_INDICATORS_SUPPRESS": "/tutorial/indicators/suppress", + "USERS": "/users", + "ME": "/users/@me", + "DELETE_ACCOUNT": "/users/@me/delete", + "DISABLE_ACCOUNT": "/users/@me/disable", + "DEVICES": "/users/@me/devices", + "SETTINGS": "/users/@me/settings", + "SETTINGS_CONSENT": "/users/@me/consent", + "PHONE": "/users/@me/phone", + "VERIFY_PHONE": "/users/@me/phone/verify", + "VERIFY_PHONE_NEW": "/phone-verifications/verify", + "RESEND_PHONE": "/phone-verifications/resend", + "CONNECTIONS": "/users/@me/connections", + "CONNECTION_SYNC_CONTACTS": "/users/@me/connections/contacts/@me/external-friend-list-entries", + "NOTES": "/users/@me/notes", + "MENTIONS": "/users/@me/mentions", + "CAPTCHA": "/users/@me/captcha/verify", + "EXPERIMENTS": "/experiments", + "LOGIN": "/auth/login", + "LOGIN_MFA": "/auth/mfa/totp", + "LOGIN_SMS": "/auth/mfa/sms", + "LOGIN_SMS_SEND": "/auth/mfa/sms/send", + "REMOTE_AUTH_INITIALIZE": "/users/@me/remote-auth", + "REMOTE_AUTH_CANCEL": "/users/@me/remote-auth/cancel", + "REMOTE_AUTH_FINISH": "/users/@me/remote-auth/finish", + "LOGOUT": "/auth/logout", + "REGISTER": "/auth/register", + "REGISTER_PHONE": "/auth/register/phone", + "TRACK": "/science", + "SSO": "/sso", + "VERIFY": "/auth/verify", + "AUTHORIZE_IP": "/auth/authorize-ip", + "VERIFY_RESEND": "/auth/verify/resend", + "FORGOT_PASSWORD": "/auth/forgot", + "RESET_PASSWORD": "/auth/reset", + "ICE": "/voice/ice", + "REPORT": "/report", + "REPORT_V2": "/reports", + "REPORT_OPTIONS": "/report/options", + "INTEGRATIONS": "/integrations", + "GATEWAY": "/gateway", + "APPLICATIONS_DETECTABLE": "/applications/detectable", + "OAUTH2_AUTHORIZE": "/oauth2/authorize", + "OAUTH2_AUTHORIZE_WEBHOOK_CHANNELS": "/oauth2/authorize/webhook-channels", + "OAUTH2_CURRENT_AUTH": "/oauth2/@me", + "OAUTH2_TOKENS": "/oauth2/tokens", + "OAUTH2_WHITELIST_ACCEPT": "/oauth2/whitelist/accept", + "MFA_TOTP_ENABLE": "/users/@me/mfa/totp/enable", + "MFA_TOTP_DISABLE": "/users/@me/mfa/totp/disable", + "MFA_SMS_ENABLE": "/users/@me/mfa/sms/enable", + "MFA_SMS_DISABLE": "/users/@me/mfa/sms/disable", + "MFA_CODES": "/users/@me/mfa/codes", + "DISABLE_EMAIL_NOTIFICATIONS": "/users/disable-email-notifications", + "GUILD_PREMIUM_SUBSCRIPTION_COOLDOWN": "/users/@me/guilds/premium/subscriptions/cooldown", + "USER_GUILD_PREMIUM_SUBSCRIPTIONS": "/users/@me/guilds/premium/subscriptions", + "USER_PREMIUM_GUILD_SUBSCRIPTION_SLOTS": "/users/@me/guilds/premium/subscription-slots", + "BILLING_STRIPE_SETUP_INTENT_SECRET": "/users/@me/billing/stripe/setup-intents", + "BILLING_PAYMENT_SOURCES": "/users/@me/billing/payment-sources", + "BILLING_PAYMENTS": "/users/@me/billing/payments", + "BILLING_BRAINTREE_POPUP_BRIDGE": "/billing/braintree/popup-bridge", + "BILLING_BRAINTREE_POPUP_BRIDGE_CALLBACK": "/billing/braintree/popup-bridge/callback", + "BILLING_SUBSCRIPTIONS": "/users/@me/billing/subscriptions", + "BILLING_APPLY_APPLE_RECEIPT": "/billing/apple/apply-receipt", + "BILLING_INVOICE_PREVIEW": "/users/@me/billing/invoices/preview", + "USER_AGREEMENTS": "/users/@me/agreements", + "HANDOFF": "/auth/handoff", + "HANDOFF_EXCHANGE": "/auth/handoff/exchange", + "LIBRARY": "/users/@me/library", + "AUTH_CONSENT_REQUIRED": "/auth/consent-required", + "USER_HARVEST": "/users/@me/harvest", + "APPLICATION_BRANCHES": "/branches", + "APPLICATIONS_PUBLIC": "/applications/public", + "APPLICATIONS_TRENDING": "/applications/trending/global", + "STORE_PUBLISHED_LISTINGS_APPLICATIONS": "/store/published-listings/applications", + "STORE_PUBLISHED_LISTINGS_SKUS": "/store/published-listings/skus", + "ENTITLEMENTS_GIFTABLE": "/users/@me/entitlements/gifts", + "PROMOTIONS": "/promotions", + "PROMOTION_ACK": "/promotions/ack", + "HYPESQUAD_ONLINE": "/hypesquad/online", + "GIFS_SEARCH": "/gifs/search", + "GIFS_TRENDING": "/gifs/trending", + "GIFS_TRENDING_GIFS": "/gifs/trending-gifs", + "GIFS_SELECT": "/gifs/select", + "GIFS_SUGGEST": "/gifs/suggest", + "GIFS_TRENDING_SEARCH": "/gifs/trending-search", + "USER_GIFT_CODE_CREATE": "/users/@me/entitlements/gift-codes", + "USER_GIFT_CODES": "/users/@me/entitlements/gift-codes", + "GUILD_DISCOVERY": "/discoverable-guilds", + "GUILD_DISCOVERY_CATEGORIES": "/discovery/categories", + "GUILD_DISCOVERY_VALID_TERM": "/discovery/valid-term", + "USER_AFFINITIES": "/users/@me/affinities/users", + "GUILD_AFFINITIES": "/users/@me/affinities/guilds", + "XBOX_GAME_PASS_PROMOTION": "/promotions/xbox-game-pass", + "XBOX_GAME_PASS_PROMOTION_REDEEM": "/promotions/xbox-game-pass/redeem", + "FUNIMATION_PROMOTION": "/promotions/funimation", + "PARTNERS_CONNECTIONS": "/partners/connections", + "PARTNERS_APPLY": "/partners/apply", + "USER_STICKER_PACKS": "/users/@me/sticker-packs", + "INTERACTIONS": "/interactions" +} diff --git a/package-lock.json b/package-lock.json index 3cb81e98..e13791d1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4614,7 +4614,7 @@ }, "node_modules/fosscord-server-util": { "version": "1.0.0", - "resolved": "git+ssh://git@github.com/fosscord/fosscord-server-util.git#9d06aa09bf8e1b44766d502a5549ac49fcb79e4c", + "resolved": "git+ssh://git@github.com/fosscord/fosscord-server-util.git#e5f408be0889562f6fa36ac1bb1730e50bf1951f", "license": "ISC", "dependencies": { "jsonwebtoken": "^8.5.1", @@ -16151,7 +16151,7 @@ "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" }, "fosscord-server-util": { - "version": "git+ssh://git@github.com/fosscord/fosscord-server-util.git#9d06aa09bf8e1b44766d502a5549ac49fcb79e4c", + "version": "git+ssh://git@github.com/fosscord/fosscord-server-util.git#e5f408be0889562f6fa36ac1bb1730e50bf1951f", "from": "fosscord-server-util@github:fosscord/fosscord-server-util", "requires": { "jsonwebtoken": "^8.5.1", diff --git a/src/Server.ts b/src/Server.ts index 3bc346e3..19a0fc5f 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -90,7 +90,7 @@ export class DiscordServer extends Server { ...req.headers, }, }); - const buffer = await response.text(); + const buffer = await response.buffer(); response.headers.forEach((value, name) => { if ( diff --git a/src/util/Member.ts b/src/util/Member.ts index 319eab60..2b268597 100644 --- a/src/util/Member.ts +++ b/src/util/Member.ts @@ -29,8 +29,6 @@ export async function addMember(user_id: bigint, guild_id: bigint, cache?: { gui const user = await getPublicUser(user_id, { guilds: true }); const guildSize = user.guilds.length; - // @ts-ignore - user.guilds = undefined; const { maxGuilds } = Config.get().limits.user; if (guildSize >= maxGuilds) { -- cgit 1.5.1 From af6f9b57ad4a7fd05d4ffa19440012084fb5071f Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Tue, 6 Apr 2021 04:30:04 +0200 Subject: :bug: fix user guilds --- src/routes/auth/register.ts | 3 +++ src/util/User.ts | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'src/util') diff --git a/src/routes/auth/register.ts b/src/routes/auth/register.ts index ce54b940..9543e814 100644 --- a/src/routes/auth/register.ts +++ b/src/routes/auth/register.ts @@ -165,6 +165,8 @@ router.post( }); } + // TODO: save date_of_birth + // constructing final user object // TODO fix: // @ts-ignore @@ -179,6 +181,7 @@ router.post( mfa_enabled: false, verified: false, email: adjusted_email, + nsfw_allowed: true, // TODO: depending on age flags: 0n, // TODO: generate default flags guilds: [], user_data: { diff --git a/src/util/User.ts b/src/util/User.ts index 1b13e153..3658e46d 100644 --- a/src/util/User.ts +++ b/src/util/User.ts @@ -16,7 +16,9 @@ export async function getPublicUser(user_id: bigint, additional_fields?: any) { ...PublicUserProjection, ...additional_fields, } - ).exec(); + ) + .lean() + .exec(); if (!user) throw new HTTPError("User not found", 404); return user; } -- cgit 1.5.1 From 79894e6f27cf1ac116705db9b87e38456c16934a Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Tue, 6 Apr 2021 17:12:05 +0200 Subject: :bug: fix body parser empty error object --- src/util/instanceOf.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'src/util') diff --git a/src/util/instanceOf.ts b/src/util/instanceOf.ts index 869f56d4..b4a231ba 100644 --- a/src/util/instanceOf.ts +++ b/src/util/instanceOf.ts @@ -121,7 +121,8 @@ export function instanceOf( return ( value.every((val, i) => { errors[i] = {}; - return ( + + if ( instanceOf(type[0], val, { path: `${path}[${i}]`, optional, @@ -129,7 +130,12 @@ export function instanceOf( req, ref: { key: i, obj: value }, }) === true - ); + ) { + delete errors[i]; + return true; + } + + return false; }) || errors ); } else if (type?.constructor?.name != "Object") { @@ -170,7 +176,7 @@ export function instanceOf( if (OPTIONAL) newKey = newKey.slice(OPTIONAL_PREFIX.length); errors[newKey] = {}; - return ( + if ( instanceOf(type[key], value[newKey], { path: `${path}.${newKey}`, optional: OPTIONAL, @@ -178,7 +184,12 @@ export function instanceOf( req, ref: { key: newKey, obj: value }, }) === true - ); + ) { + delete errors[newKey]; + return true; + } + + return false; }) || errors ); } else if (typeof type === "number" || typeof type === "string" || typeof type === "boolean") { -- cgit 1.5.1 From 70892870161edad2a44ae36bdf9092961ef830bb Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Tue, 6 Apr 2021 18:02:10 +0200 Subject: :art: Convert id bigint to string --- src/middlewares/Authentication.ts | 2 +- src/routes/auth/login.ts | 17 ++++++++++++----- src/routes/auth/register.ts | 22 ++++++++++++++++++---- src/routes/channels/#channel_id/invites.ts | 4 ++-- .../channels/#channel_id/messages/bulk-delete.ts | 6 +++--- src/routes/channels/#channel_id/messages/index.ts | 10 +++++----- src/routes/guilds/#id/bans.ts | 14 +++++++------- src/routes/guilds/#id/channels.ts | 4 ++-- src/routes/guilds/#id/index.ts | 6 +++--- src/routes/guilds/#id/members.ts | 10 +++++----- src/routes/users/@me/guilds.ts | 2 +- src/schema/Channel.ts | 10 +++++----- src/schema/Guild.ts | 14 +++++++------- src/schema/Message.ts | 12 ++++++------ src/test/mongo_test.ts | 5 ++--- src/util/Config.ts | 2 +- src/util/Member.ts | 4 ++-- src/util/User.ts | 2 +- 18 files changed, 83 insertions(+), 63 deletions(-) (limited to 'src/util') diff --git a/src/middlewares/Authentication.ts b/src/middlewares/Authentication.ts index 595bcf73..f2cd438c 100644 --- a/src/middlewares/Authentication.ts +++ b/src/middlewares/Authentication.ts @@ -29,7 +29,7 @@ export async function Authentication(req: Request, res: Response, next: NextFunc const decoded: any = await checkToken(req.headers.authorization); req.token = decoded; - req.user_id = BigInt(decoded.id); + req.user_id = decoded.id; return next(); } catch (error) { return next(new HTTPError(error.toString(), 400)); diff --git a/src/routes/auth/login.ts b/src/routes/auth/login.ts index b0936104..3c279319 100644 --- a/src/routes/auth/login.ts +++ b/src/routes/auth/login.ts @@ -25,12 +25,20 @@ router.post( const query: any[] = [{ phone: login }]; if (email) query.push({ email }); - // * MongoDB Specific query for user with same email or phone number const user = await UserModel.findOne( { $or: query, }, - `user_data.hash id user_settings.locale user_settings.theme` + { + id: true, + user_settings: { + locale: true, + theme: true, + }, + user_data: { + hash: true, + }, + } ).exec(); if (!user) { @@ -57,13 +65,13 @@ router.post( } ); -export async function generateToken(id: bigint) { +export async function generateToken(id: string) { const iat = Math.floor(Date.now() / 1000); const algorithm = "HS256"; return new Promise((res, rej) => { jwt.sign( - { id: `${id}`, iat }, + { id: id, iat }, Config.get().security.jwtSecret, { algorithm, @@ -80,7 +88,6 @@ export async function generateToken(id: bigint) { * POST /auth/login * @argument { login: "email@gmail.com", password: "cleartextpassword", undelete: false, captcha_key: null, login_source: null, gift_code_sku_id: null, } - * MFA required: * @returns {"token": null, "mfa": true, "sms": true, "ticket": "SOME TICKET JWT TOKEN"} diff --git a/src/routes/auth/register.ts b/src/routes/auth/register.ts index 9543e814..5fbe610e 100644 --- a/src/routes/auth/register.ts +++ b/src/routes/auth/register.ts @@ -166,10 +166,9 @@ router.post( } // TODO: save date_of_birth + // appearently discord doesn't save the date of birth and just calculate if nsfw is allowed + // if nsfw_allowed is null/undefined it'll require date_of_birth to set it to true/false - // constructing final user object - // TODO fix: - // @ts-ignore const user: User = { id: Snowflake.generate(), created_at: new Date(), @@ -178,10 +177,25 @@ router.post( avatar: null, bot: false, system: false, + desktop: false, + mobile: false, + premium: false, + premium_type: 0, + phone: undefined, mfa_enabled: false, verified: false, + presence: { + activities: [], + client_status: { + desktop: undefined, + mobile: undefined, + web: undefined, + }, + status: "offline", + }, email: adjusted_email, nsfw_allowed: true, // TODO: depending on age + public_flags: 0n, flags: 0n, // TODO: generate default flags guilds: [], user_data: { @@ -233,7 +247,7 @@ router.post( }; // insert user into database - await new UserModel(user).save({}); + await new UserModel(user).save(); return res.json({ token: await generateToken(user.id) }); } diff --git a/src/routes/channels/#channel_id/invites.ts b/src/routes/channels/#channel_id/invites.ts index c9910ae2..adfb0688 100644 --- a/src/routes/channels/#channel_id/invites.ts +++ b/src/routes/channels/#channel_id/invites.ts @@ -13,7 +13,7 @@ const router: Router = Router(); router.post("/", check(InviteCreateSchema), async (req: Request, res: Response) => { const usID = req.user_id; - const chID = BigInt(req.params.channel_id); + const chID = req.params.channel_id; const channel = await ChannelModel.findOne({ id: chID }).exec(); if (!channel || !channel.guild_id) { @@ -47,7 +47,7 @@ router.post("/", check(InviteCreateSchema), async (req: Request, res: Response) router.get("/", async (req: Request, res: Response) => { const usID = req.user_id; - const chID = BigInt(req.params.channel_id); + const chID = req.params.channel_id; const channel = await ChannelModel.findOne({ id: chID }).exec(); if (!channel || !channel.guild_id) { diff --git a/src/routes/channels/#channel_id/messages/bulk-delete.ts b/src/routes/channels/#channel_id/messages/bulk-delete.ts index f5c9afc7..89e9d720 100644 --- a/src/routes/channels/#channel_id/messages/bulk-delete.ts +++ b/src/routes/channels/#channel_id/messages/bulk-delete.ts @@ -12,8 +12,8 @@ export default router; // TODO: should users be able to bulk delete messages or only bots? // TODO: should this request fail, if you provide messages older than 14 days/invalid ids? // https://discord.com/developers/docs/resources/channel#bulk-delete-messages -router.post("/", check({ messages: [BigInt] }), async (req, res) => { - const channel_id = BigInt(req.params.channel_id); +router.post("/", check({ messages: [String] }), async (req, res) => { + const channel_id = req.params.channel_id const channel = await ChannelModel.findOne({ id: channel_id }, { permission_overwrites: true, guild_id: true }).exec(); if (!channel?.guild_id) throw new HTTPError("Can't bulk delete dm channel messages", 400); @@ -22,7 +22,7 @@ router.post("/", check({ messages: [BigInt] }), async (req, res) => { const { maxBulkDelete } = Config.get().limits.message; - const { messages } = req.body as { messages: bigint[] }; + const { messages } = req.body as { messages: string[] }; if (messages.length < 2) throw new HTTPError("You must at least specify 2 messages to bulk delete"); if (messages.length > maxBulkDelete) throw new HTTPError(`You cannot delete more than ${maxBulkDelete} messages`); diff --git a/src/routes/channels/#channel_id/messages/index.ts b/src/routes/channels/#channel_id/messages/index.ts index 13c819b4..0b91a977 100644 --- a/src/routes/channels/#channel_id/messages/index.ts +++ b/src/routes/channels/#channel_id/messages/index.ts @@ -27,23 +27,23 @@ function isTextChannel(type: ChannelType): boolean { // https://discord.com/developers/docs/resources/channel#create-message // get messages router.get("/", async (req, res) => { - const channel_id = BigInt(req.params.channel_id); + const channel_id = req.params.channel_id; const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true, type: true, permission_overwrites: true }).exec(); if (!channel) throw new HTTPError("Channel not found", 404); isTextChannel(channel.type); try { - instanceOf({ $around: BigInt, $after: BigInt, $before: BigInt, $limit: new Length(Number, 1, 100) }, req.query, { + instanceOf({ $around: String, $after: String, $before: String, $limit: new Length(Number, 1, 100) }, req.query, { path: "query", req, }); } catch (error) { return res.status(400).json({ code: 50035, message: "Invalid Query", success: false, errors: error }); } - var { around, after, before, limit }: { around?: bigint; after?: bigint; before?: bigint; limit?: number } = req.query; + var { around, after, before, limit }: { around?: string; after?: string; before?: string; limit?: number } = req.query; if (!limit) limit = 50; - var halfLimit = BigInt(Math.floor(limit / 2)); + var halfLimit = Math.floor(limit / 2); if ([ChannelType.GUILD_VOICE, ChannelType.GUILD_CATEGORY, ChannelType.GUILD_STORE].includes(channel.type)) throw new HTTPError("Not a text channel"); @@ -89,7 +89,7 @@ const messageUpload = multer({ limits: { fieldSize: 1024 * 1024 * 1024 * 50 } }) // TODO: trim and replace message content and every embed field // Send message router.post("/", check(MessageCreateSchema), async (req, res) => { - const channel_id = BigInt(req.params.channel_id); + const channel_id = req.params.channel_id; const body = req.body as MessageCreateSchema; const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true, type: true, permission_overwrites: true }).exec(); diff --git a/src/routes/guilds/#id/bans.ts b/src/routes/guilds/#id/bans.ts index ba062a44..e66ae3d4 100644 --- a/src/routes/guilds/#id/bans.ts +++ b/src/routes/guilds/#id/bans.ts @@ -11,7 +11,7 @@ import { getPublicUser } from "../../../util/User"; const router: Router = Router(); router.get("/", async (req: Request, res: Response) => { - const guild_id = BigInt(req.params.id); + const guild_id = req.params.id; const guild = await GuildModel.findOne({ id: guild_id }).exec(); if (!guild) throw new HTTPError("Guild not found", 404); @@ -21,8 +21,8 @@ router.get("/", async (req: Request, res: Response) => { }); router.get("/:user", async (req: Request, res: Response) => { - const guild_id = BigInt(req.params.id); - const user_id = BigInt(req.params.ban); + const guild_id = req.params.id; + const user_id = req.params.ban; var ban = await BanModel.findOne({ guild_id: guild_id, user_id: user_id }).exec(); if (!ban) throw new HTTPError("Ban not found", 404); @@ -30,8 +30,8 @@ router.get("/:user", async (req: Request, res: Response) => { }); router.post("/:user_id", check(BanCreateSchema), async (req: Request, res: Response) => { - const guild_id = BigInt(req.params.id); - const banned_user_id = BigInt(req.params.user_id); + const guild_id = req.params.id; + const banned_user_id = req.params.user_id; const banned_user = await getPublicUser(banned_user_id); const perms = await getPermission(req.user_id, guild_id); @@ -61,8 +61,8 @@ router.post("/:user_id", check(BanCreateSchema), async (req: Request, res: Respo }); router.delete("/:user_id", async (req: Request, res: Response) => { - var guild_id = BigInt(req.params.id); - var banned_user_id = BigInt(req.params.user_id); + var guild_id = req.params.id; + var banned_user_id = req.params.user_id; const banned_user = await getPublicUser(banned_user_id); const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); diff --git a/src/routes/guilds/#id/channels.ts b/src/routes/guilds/#id/channels.ts index df41ec41..cd03fdbb 100644 --- a/src/routes/guilds/#id/channels.ts +++ b/src/routes/guilds/#id/channels.ts @@ -6,14 +6,14 @@ import { check } from "../../../util/instanceOf"; const router = Router(); router.get("/", async (req, res) => { - const guild_id = BigInt(req.params.id); + const guild_id = (req.params.id); const channels = await ChannelModel.find({ guild_id }).lean().exec(); res.json(channels); }); router.post("/", check(ChannelModifySchema), async (req, res) => { - const guild_id = BigInt(req.params.id); + const guild_id = (req.params.id); const body = req.body as ChannelModifySchema; if (!body.permission_overwrites) body.permission_overwrites = []; if (!body.topic) body.topic = ""; diff --git a/src/routes/guilds/#id/index.ts b/src/routes/guilds/#id/index.ts index 9b5ce313..385904f6 100644 --- a/src/routes/guilds/#id/index.ts +++ b/src/routes/guilds/#id/index.ts @@ -19,7 +19,7 @@ import { check } from "../../../util/instanceOf"; const router = Router(); router.get("/", async (req: Request, res: Response) => { - const guild_id = BigInt(req.params.id); + const guild_id = req.params.id; const guild = await GuildModel.findOne({ id: guild_id }).exec(); if (!guild) throw new HTTPError("Guild does not exist", 404); @@ -32,7 +32,7 @@ router.get("/", async (req: Request, res: Response) => { router.patch("/", check(GuildUpdateSchema), async (req: Request, res: Response) => { const body = req.body as GuildUpdateSchema; - const guild_id = BigInt(req.params.id); + const guild_id = req.params.id; const guild = await GuildModel.findOne({ id: guild_id }).exec(); if (!guild) throw new HTTPError("This guild does not exist", 404); @@ -45,7 +45,7 @@ router.patch("/", check(GuildUpdateSchema), async (req: Request, res: Response) }); router.delete("/", async (req: Request, res: Response) => { - var guild_id = BigInt(req.params.id); + var guild_id = req.params.id; const guild = await GuildModel.findOne({ id: guild_id }, "owner_id").exec(); if (!guild) throw new HTTPError("This guild does not exist", 404); diff --git a/src/routes/guilds/#id/members.ts b/src/routes/guilds/#id/members.ts index 25889e2e..f95bd313 100644 --- a/src/routes/guilds/#id/members.ts +++ b/src/routes/guilds/#id/members.ts @@ -10,12 +10,12 @@ const router = Router(); // TODO: not allowed for user -> only allowed for bots with privileged intents // TODO: send over websocket router.get("/", async (req: Request, res: Response) => { - const guild_id = BigInt(req.params.id); + const guild_id = req.params.id; const guild = await GuildModel.findOne({ id: guild_id }).exec(); if (!guild) throw new HTTPError("Guild not found", 404); try { - instanceOf({ $limit: new Length(Number, 1, 1000), $after: BigInt }, req.query, { + instanceOf({ $limit: new Length(Number, 1, 1000), $after: String }, req.query, { path: "query", req, ref: { obj: null, key: "" }, @@ -26,7 +26,7 @@ router.get("/", async (req: Request, res: Response) => { // @ts-ignore if (!req.query.limit) req.query.limit = 1; - const { limit, after } = (req.query) as { limit: number; after: bigint }; + const { limit, after } = (req.query) as { limit: number; after: string }; const query = after ? { id: { $gt: after } } : {}; var members = await MemberModel.find({ guild_id, ...query }, PublicMemberProjection) @@ -39,8 +39,8 @@ router.get("/", async (req: Request, res: Response) => { }); router.get("/:member", async (req: Request, res: Response) => { - const guild_id = BigInt(req.params.id); - const user_id = BigInt(req.params.member); + const guild_id = req.params.id; + const user_id = req.params.member; const member = await MemberModel.findOne({ id: user_id, guild_id }).populate({ path: "user", select: PublicUserProjection }).exec(); if (!member) throw new HTTPError("Member not found", 404); diff --git a/src/routes/users/@me/guilds.ts b/src/routes/users/@me/guilds.ts index 1b87b51d..6b9243ac 100644 --- a/src/routes/users/@me/guilds.ts +++ b/src/routes/users/@me/guilds.ts @@ -19,7 +19,7 @@ router.get("/", async (req: Request, res: Response) => { // user send to leave a certain guild router.delete("/:id", async (req: Request, res: Response) => { - const guildID = BigInt(req.params.id); + const guildID = (req.params.id); const guild = await GuildModel.findOne({ id: guildID }).exec(); if (!guild) throw new HTTPError("Guild doesn't exist", 404); diff --git a/src/schema/Channel.ts b/src/schema/Channel.ts index 2e7d1214..0fafc54d 100644 --- a/src/schema/Channel.ts +++ b/src/schema/Channel.ts @@ -10,7 +10,7 @@ export const ChannelModifySchema = { $position: Number, $permission_overwrites: [ { - id: BigInt, + id: String, type: new Length(Number, 0, 1), // either 0 (role) or 1 (member) allow: BigInt, deny: BigInt, @@ -29,23 +29,23 @@ export interface ChannelModifySchema { rate_limit_per_user?: Number; position?: number; permission_overwrites?: { - id: bigint; + id: string; type: number; allow: bigint; deny: bigint; }[]; - parent_id?: bigint; + parent_id?: string; nsfw?: boolean; } export const ChannelGuildPositionUpdateSchema = [ { - id: BigInt, + id: String, $position: Number, }, ]; export type ChannelGuildPositionUpdateSchema = { - id: bigint; + id: string; position?: number; }[]; diff --git a/src/schema/Guild.ts b/src/schema/Guild.ts index d8c3431d..6527f35d 100644 --- a/src/schema/Guild.ts +++ b/src/schema/Guild.ts @@ -7,7 +7,7 @@ export const GuildCreateSchema = { $icon: String, $channels: [Object], $guild_template_code: String, - $system_channel_id: BigInt, + $system_channel_id: String, }; export interface GuildCreateSchema { @@ -16,7 +16,7 @@ export interface GuildCreateSchema { icon?: string; channels?: GuildChannel[]; guild_template_code?: string; - system_channel_id?: bigint; + system_channel_id?: string; } export const GuildUpdateSchema = { @@ -29,11 +29,11 @@ export const GuildUpdateSchema = { $verification_level: Number, $default_message_notifications: Number, $system_channel_flags: Number, - $system_channel_id: BigInt, + $system_channel_id: String, $explicit_content_filter: Number, - $public_updates_channel_id: BigInt, + $public_updates_channel_id: String, $afk_timeout: Number, - $afk_channel_id: BigInt, + $afk_channel_id: String, }; // @ts-ignore delete GuildUpdateSchema.$channels; @@ -47,9 +47,9 @@ export interface GuildUpdateSchema extends Omit { default_message_notifications?: number; system_channel_flags?: number; explicit_content_filter?: number; - public_updates_channel_id?: bigint; + public_updates_channel_id?: string; afk_timeout?: number; - afk_channel_id?: bigint; + afk_channel_id?: string; } export const GuildGetSchema = { diff --git a/src/schema/Message.ts b/src/schema/Message.ts index 4ae6c136..0c682a00 100644 --- a/src/schema/Message.ts +++ b/src/schema/Message.ts @@ -44,9 +44,9 @@ export const MessageCreateSchema = { }, $allowed_mentions: [], $message_reference: { - message_id: BigInt, - channel_id: BigInt, - $guild_id: BigInt, + message_id: String, + channel_id: String, + $guild_id: String, $fail_if_not_exists: Boolean, }, $payload_json: String, @@ -60,9 +60,9 @@ export interface MessageCreateSchema { embed?: Embed & { timestamp: string }; allowed_mentions?: []; message_reference?: { - message_id: bigint; - channel_id: bigint; - guild_id?: bigint; + message_id: string; + channel_id: string; + guild_id?: string; fail_if_not_exists: boolean; }; payload_json?: string; diff --git a/src/test/mongo_test.ts b/src/test/mongo_test.ts index f1a7f3f6..44b04c5b 100644 --- a/src/test/mongo_test.ts +++ b/src/test/mongo_test.ts @@ -1,13 +1,12 @@ import mongoose, { Schema, Types } from "mongoose"; -import { Long as MongoTypeLong } from "mongodb"; require("mongoose-long")(mongoose); const userSchema = new Schema({ - id: MongoTypeLong, + id: String, }); const messageSchema = new Schema({ - id: MongoTypeLong, + id: String, content: String, }); const message = mongoose.model("message", messageSchema, "messages"); diff --git a/src/util/Config.ts b/src/util/Config.ts index a9cbddde..60d83e1a 100644 --- a/src/util/Config.ts +++ b/src/util/Config.ts @@ -23,7 +23,7 @@ export interface RateLimit { export interface DefaultOptions { general: { - instance_id: bigint; + instance_id: string; }; permissions: { user: { diff --git a/src/util/Member.ts b/src/util/Member.ts index 2b268597..3ce06962 100644 --- a/src/util/Member.ts +++ b/src/util/Member.ts @@ -25,7 +25,7 @@ export const PublicMemberProjection = { premium_since: true, }; -export async function addMember(user_id: bigint, guild_id: bigint, cache?: { guild?: Guild }) { +export async function addMember(user_id: string, guild_id: string, cache?: { guild?: Guild }) { const user = await getPublicUser(user_id, { guilds: true }); const guildSize = user.guilds.length; @@ -83,7 +83,7 @@ export async function addMember(user_id: bigint, guild_id: bigint, cache?: { gui ]); } -export async function removeMember(user_id: bigint, guild_id: bigint) { +export async function removeMember(user_id: string, guild_id: string) { const user = await getPublicUser(user_id); const guild = await GuildModel.findOne({ id: guild_id }, { owner_id: true }).exec(); diff --git a/src/util/User.ts b/src/util/User.ts index 3658e46d..70098bb5 100644 --- a/src/util/User.ts +++ b/src/util/User.ts @@ -9,7 +9,7 @@ export const PublicUserProjection = { avatar: true, }; -export async function getPublicUser(user_id: bigint, additional_fields?: any) { +export async function getPublicUser(user_id: string, additional_fields?: any) { const user = await UserModel.findOne( { id: user_id }, { -- cgit 1.5.1 From b32beb0b9c9f19a3444d87aa7369912e54befa90 Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Wed, 7 Apr 2021 03:03:27 +0200 Subject: :bug: fix lean not working with virtuals --- src/routes/channels/#channel_id/invites.ts | 35 ++++++++++++----------- src/routes/channels/#channel_id/messages/index.ts | 18 +++++++++--- src/routes/guilds/#id/bans.ts | 6 ++-- src/routes/guilds/#id/channels.ts | 13 +++++---- src/routes/guilds/#id/members.ts | 5 ++-- src/routes/users/@me/guilds.ts | 10 +++---- src/util/User.ts | 8 ++---- 7 files changed, 52 insertions(+), 43 deletions(-) (limited to 'src/util') diff --git a/src/routes/channels/#channel_id/invites.ts b/src/routes/channels/#channel_id/invites.ts index adfb0688..da802800 100644 --- a/src/routes/channels/#channel_id/invites.ts +++ b/src/routes/channels/#channel_id/invites.ts @@ -7,21 +7,21 @@ import { emitEvent } from "../../../util/Event"; import { InviteCreateSchema } from "../../../schema/Invite"; -import { getPermission, ChannelModel, InviteModel, InviteCreateEvent } from "fosscord-server-util"; +import { getPermission, ChannelModel, InviteModel, InviteCreateEvent, toObject } from "fosscord-server-util"; const router: Router = Router(); router.post("/", check(InviteCreateSchema), async (req: Request, res: Response) => { - const usID = req.user_id; - const chID = req.params.channel_id; - const channel = await ChannelModel.findOne({ id: chID }).exec(); + const { user_id } = req; + const { channel_id } = req.params; + const channel = await ChannelModel.findOne({ id: channel_id }).exec(); if (!channel || !channel.guild_id) { throw new HTTPError("This channel doesn't exist", 404); } - const { guild_id: guID } = channel; + const { guild_id } = channel; - const permission = await getPermission(usID, guID); + const permission = await getPermission(user_id, guild_id); if (!permission.has("CREATE_INSTANT_INVITE")) { throw new HTTPError("You aren't authorised to access this endpoint", 401); @@ -34,34 +34,35 @@ router.post("/", check(InviteCreateSchema), async (req: Request, res: Response) max_uses: req.body.max_uses, max_age: req.body.max_age, created_at: new Date(), - guild_id: guID, - channel_id: chID, - inviter_id: usID, + guild_id, + channel_id: channel_id, + inviter_id: user_id, }; await new InviteModel(invite).save(); - await emitEvent({ event: "INVITE_CREATE", data: invite } as InviteCreateEvent); + await emitEvent({ event: "INVITE_CREATE", data: invite, guild_id } as InviteCreateEvent); res.status(201).send(invite); }); router.get("/", async (req: Request, res: Response) => { - const usID = req.user_id; - const chID = req.params.channel_id; - const channel = await ChannelModel.findOne({ id: chID }).exec(); + const { user_id } = req; + const { channel_id } = req.params; + const channel = await ChannelModel.findOne({ id: channel_id }).exec(); if (!channel || !channel.guild_id) { throw new HTTPError("This channel doesn't exist", 404); } - const { guild_id: guID } = channel; - const permission = await getPermission(usID, guID); + const { guild_id } = channel; + const permission = await getPermission(user_id, guild_id); if (!permission.has("MANAGE_CHANNELS")) { throw new HTTPError("You aren't authorised to access this endpoint", 401); } - const invites = await InviteModel.find({ guild_id: guID }).lean().exec(); - res.status(200).send(invites); + const invites = await InviteModel.find({ guild_id }).exec(); + + res.status(200).send(toObject(invites)); }); export default router; diff --git a/src/routes/channels/#channel_id/messages/index.ts b/src/routes/channels/#channel_id/messages/index.ts index 7b4b3ec0..cba1d7f0 100644 --- a/src/routes/channels/#channel_id/messages/index.ts +++ b/src/routes/channels/#channel_id/messages/index.ts @@ -1,11 +1,22 @@ import { Router } from "express"; -import { ChannelModel, ChannelType, getPermission, Message, MessageCreateEvent, MessageModel, Snowflake } from "fosscord-server-util"; +import { + ChannelModel, + ChannelType, + getPermission, + Message, + MessageCreateEvent, + MessageDocument, + MessageModel, + Snowflake, + toObject, +} from "fosscord-server-util"; import { HTTPError } from "lambert-server"; import { MessageCreateSchema } from "../../../../schema/Message"; import { check, instanceOf, Length } from "../../../../util/instanceOf"; import { PublicUserProjection } from "../../../../util/User"; import multer from "multer"; import { emitEvent } from "../../../../util/Event"; +import { Query } from "mongoose"; const router: Router = Router(); export default router; @@ -57,7 +68,7 @@ router.get("/", async (req, res) => { if (!channel.recipients.includes(req.user_id)) throw new HTTPError("You don't have permission to view this channel", 401); } - var query: any; + var query: Query; if (after) query = MessageModel.find({ channel_id, id: { $gt: after } }); else if (before) query = MessageModel.find({ channel_id, id: { $lt: before } }); else if (around) @@ -76,10 +87,9 @@ router.get("/", async (req, res) => { .populate({ path: "mention_channels", select: { id: true, guild_id: true, type: true, name: true } }) .populate("mention_roles") // .populate({ path: "member", select: PublicMemberProjection }) - .lean() .exec(); - return res.json(messages); + return res.json(toObject(messages)); }); // TODO: config max upload size diff --git a/src/routes/guilds/#id/bans.ts b/src/routes/guilds/#id/bans.ts index e66ae3d4..5ac92154 100644 --- a/src/routes/guilds/#id/bans.ts +++ b/src/routes/guilds/#id/bans.ts @@ -1,5 +1,5 @@ import { Request, Response, Router } from "express"; -import { BanModel, getPermission, GuildBanAddEvent, GuildBanRemoveEvent, GuildModel } from "fosscord-server-util"; +import { BanModel, getPermission, GuildBanAddEvent, GuildBanRemoveEvent, GuildModel, toObject } from "fosscord-server-util"; import { HTTPError } from "lambert-server"; import { getIpAdress } from "../../../middlewares/GlobalRateLimit"; import { BanCreateSchema } from "../../../schema/Ban"; @@ -16,8 +16,8 @@ router.get("/", async (req: Request, res: Response) => { const guild = await GuildModel.findOne({ id: guild_id }).exec(); if (!guild) throw new HTTPError("Guild not found", 404); - var bans = await BanModel.find({ guild_id: guild_id }).lean().exec(); - return res.json(bans); + var bans = await BanModel.find({ guild_id: guild_id }).exec(); + return res.json(toObject(bans)); }); router.get("/:user", async (req: Request, res: Response) => { diff --git a/src/routes/guilds/#id/channels.ts b/src/routes/guilds/#id/channels.ts index cd03fdbb..b949def0 100644 --- a/src/routes/guilds/#id/channels.ts +++ b/src/routes/guilds/#id/channels.ts @@ -1,19 +1,20 @@ import { Router } from "express"; -import { ChannelModel, ChannelType, GuildModel, Snowflake } from "fosscord-server-util"; +import { ChannelCreateEvent, ChannelModel, ChannelType, GuildModel, Snowflake, toObject } from "fosscord-server-util"; import { HTTPError } from "lambert-server"; import { ChannelModifySchema } from "../../../schema/Channel"; +import { emitEvent } from "../../../util/Event"; import { check } from "../../../util/instanceOf"; const router = Router(); router.get("/", async (req, res) => { - const guild_id = (req.params.id); - const channels = await ChannelModel.find({ guild_id }).lean().exec(); + const guild_id = req.params.id; + const channels = await ChannelModel.find({ guild_id }).exec(); - res.json(channels); + res.json(toObject(channels)); }); router.post("/", check(ChannelModifySchema), async (req, res) => { - const guild_id = (req.params.id); + const guild_id = req.params.id; const body = req.body as ChannelModifySchema; if (!body.permission_overwrites) body.permission_overwrites = []; if (!body.topic) body.topic = ""; @@ -45,6 +46,8 @@ router.post("/", check(ChannelModifySchema), async (req, res) => { }; await new ChannelModel(channel).save(); + await emitEvent({ event: "CHANNEL_CREATE", data: channel, guild_id } as ChannelCreateEvent); + res.json(channel); }); diff --git a/src/routes/guilds/#id/members.ts b/src/routes/guilds/#id/members.ts index f95bd313..1c3cb33d 100644 --- a/src/routes/guilds/#id/members.ts +++ b/src/routes/guilds/#id/members.ts @@ -1,5 +1,5 @@ import { Request, Response, Router } from "express"; -import { GuildModel, MemberModel } from "fosscord-server-util"; +import { GuildModel, MemberModel, toObject } from "fosscord-server-util"; import { HTTPError } from "lambert-server"; import { instanceOf, Length } from "../../../util/instanceOf"; import { PublicMemberProjection } from "../../../util/Member"; @@ -32,10 +32,9 @@ router.get("/", async (req: Request, res: Response) => { var members = await MemberModel.find({ guild_id, ...query }, PublicMemberProjection) .limit(limit) .populate({ path: "user", select: PublicUserProjection }) - .lean() .exec(); - return res.json(members); + return res.json(toObject(members)); }); router.get("/:member", async (req: Request, res: Response) => { diff --git a/src/routes/users/@me/guilds.ts b/src/routes/users/@me/guilds.ts index 6b9243ac..e04107ac 100644 --- a/src/routes/users/@me/guilds.ts +++ b/src/routes/users/@me/guilds.ts @@ -1,5 +1,5 @@ import { Router, Request, Response } from "express"; -import { GuildModel, MemberModel, UserModel, GuildDeleteEvent, GuildMemberRemoveEvent } from "fosscord-server-util"; +import { GuildModel, MemberModel, UserModel, GuildDeleteEvent, GuildMemberRemoveEvent, toObject } from "fosscord-server-util"; import { HTTPError } from "lambert-server"; import { emitEvent } from "../../../util/Event"; import { getPublicUser } from "../../../util/User"; @@ -11,15 +11,13 @@ router.get("/", async (req: Request, res: Response) => { if (!user) throw new HTTPError("User not found", 404); var guildIDs = user.guilds || []; - var guild = await GuildModel.find({ id: { $in: guildIDs } }) - .lean() - .exec(); - res.json(guild); + var guild = await GuildModel.find({ id: { $in: guildIDs } }).exec(); + res.json(toObject(guild)); }); // user send to leave a certain guild router.delete("/:id", async (req: Request, res: Response) => { - const guildID = (req.params.id); + const guildID = req.params.id; const guild = await GuildModel.findOne({ id: guildID }).exec(); if (!guild) throw new HTTPError("Guild doesn't exist", 404); diff --git a/src/util/User.ts b/src/util/User.ts index 70098bb5..05213642 100644 --- a/src/util/User.ts +++ b/src/util/User.ts @@ -1,4 +1,4 @@ -import { UserModel } from "fosscord-server-util"; +import { toObject, UserModel } from "fosscord-server-util"; import { HTTPError } from "lambert-server"; export const PublicUserProjection = { @@ -16,9 +16,7 @@ export async function getPublicUser(user_id: string, additional_fields?: any) { ...PublicUserProjection, ...additional_fields, } - ) - .lean() - .exec(); + ).exec(); if (!user) throw new HTTPError("User not found", 404); - return user; + return toObject(user); } -- cgit 1.5.1 From 2a952755028789506f35e33a9f7477e8531c5382 Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Wed, 7 Apr 2021 20:25:37 +0200 Subject: :zap: use mongoose autopopulate --- src/routes/channels/#channel_id/messages/index.ts | 24 ++---- src/routes/guilds/#guild_id/bans.ts | 93 +++++++++++++++++++++++ src/routes/guilds/#guild_id/channels.ts | 54 +++++++++++++ src/routes/guilds/#guild_id/index.ts | 85 +++++++++++++++++++++ src/routes/guilds/#guild_id/members.ts | 53 +++++++++++++ src/routes/guilds/#id/bans.ts | 93 ----------------------- src/routes/guilds/#id/channels.ts | 54 ------------- src/routes/guilds/#id/index.ts | 73 ------------------ src/routes/guilds/#id/members.ts | 54 ------------- src/routes/users/@me/guilds.ts | 35 +++++---- src/util/Event.ts | 1 + src/util/Member.ts | 1 + 12 files changed, 312 insertions(+), 308 deletions(-) create mode 100644 src/routes/guilds/#guild_id/bans.ts create mode 100644 src/routes/guilds/#guild_id/channels.ts create mode 100644 src/routes/guilds/#guild_id/index.ts create mode 100644 src/routes/guilds/#guild_id/members.ts delete mode 100644 src/routes/guilds/#id/bans.ts delete mode 100644 src/routes/guilds/#id/channels.ts delete mode 100644 src/routes/guilds/#id/index.ts delete mode 100644 src/routes/guilds/#id/members.ts (limited to 'src/util') diff --git a/src/routes/channels/#channel_id/messages/index.ts b/src/routes/channels/#channel_id/messages/index.ts index 99f5fdcd..4978b98a 100644 --- a/src/routes/channels/#channel_id/messages/index.ts +++ b/src/routes/channels/#channel_id/messages/index.ts @@ -17,6 +17,7 @@ import { PublicUserProjection } from "../../../../util/User"; import multer from "multer"; import { emitEvent } from "../../../../util/Event"; import { Query } from "mongoose"; +import { PublicMemberProjection } from "../../../../util/Member"; const router: Router = Router(); export default router; @@ -80,14 +81,7 @@ router.get("/", async (req, res) => { query = MessageModel.find({ channel_id }).sort({ id: -1 }); } - const messages = await query - .limit(limit) - .populate({ path: "author", select: PublicUserProjection }) - .populate({ path: "mentions", select: PublicUserProjection }) - .populate({ path: "mention_channels", select: { id: true, guild_id: true, type: true, name: true } }) - .populate("mention_roles") - // .populate({ path: "member", select: PublicMemberProjection }) - .exec(); + const messages = await query.limit(limit).exec(); return res.json(toObject(messages)); }); @@ -147,19 +141,11 @@ router.post("/", check(MessageCreateSchema), async (req, res) => { type: 0, tts: body.tts, nonce: body.nonce, + pinned: false, }; - const doc = new MessageModel(message); - await doc.save(); - - const data = toObject( - await MessageModel.populate(doc, [ - { path: "author", select: PublicUserProjection }, - { path: "mentions", select: PublicUserProjection }, - { path: "mention_roles" }, - { path: "mention_channels", select: { id: true, guild_id: true, type: true, name: true } }, - ]) - ); + const doc = await new MessageModel(message).populate({ path: "member", select: PublicMemberProjection }).save(); + const data = toObject(doc); await emitEvent({ event: "MESSAGE_CREATE", channel_id, data, guild_id: channel.guild_id } as MessageCreateEvent); diff --git a/src/routes/guilds/#guild_id/bans.ts b/src/routes/guilds/#guild_id/bans.ts new file mode 100644 index 00000000..3de80a32 --- /dev/null +++ b/src/routes/guilds/#guild_id/bans.ts @@ -0,0 +1,93 @@ +import { Request, Response, Router } from "express"; +import { BanModel, getPermission, GuildBanAddEvent, GuildBanRemoveEvent, GuildModel, toObject } from "fosscord-server-util"; +import { HTTPError } from "lambert-server"; +import { getIpAdress } from "../../../middlewares/GlobalRateLimit"; +import { BanCreateSchema } from "../../../schema/Ban"; +import { emitEvent } from "../../../util/Event"; +import { check } from "../../../util/instanceOf"; +import { removeMember } from "../../../util/Member"; +import { getPublicUser } from "../../../util/User"; + +const router: Router = Router(); + +router.get("/", async (req: Request, res: Response) => { + const guild_id = req.params.id; + + const guild = await GuildModel.exists({ id: guild_id }); + if (!guild) throw new HTTPError("Guild not found", 404); + + var bans = await BanModel.find({ guild_id: guild_id }).exec(); + return res.json(toObject(bans)); +}); + +router.get("/:user", async (req: Request, res: Response) => { + const guild_id = req.params.id; + const user_id = req.params.ban; + + var ban = await BanModel.findOne({ guild_id: guild_id, user_id: user_id }).exec(); + if (!ban) throw new HTTPError("Ban not found", 404); + return res.json(ban); +}); + +router.post("/:user_id", check(BanCreateSchema), async (req: Request, res: Response) => { + const guild_id = req.params.id; + const banned_user_id = req.params.user_id; + + const banned_user = await getPublicUser(banned_user_id); + const perms = await getPermission(req.user_id, guild_id); + if (!perms.has("BAN_MEMBERS")) throw new HTTPError("You don't have the permission to ban members", 403); + if (req.user_id === banned_user_id) throw new HTTPError("You can't ban yourself", 400); + + await removeMember(banned_user_id, guild_id); + + const ban = await new BanModel({ + user_id: banned_user_id, + guild_id: guild_id, + ip: getIpAdress(req), + executor_id: req.user_id, + reason: req.body.reason, // || otherwise empty + }).save(); + + await emitEvent({ + event: "GUILD_BAN_ADD", + data: { + guild_id: guild_id, + user: banned_user, + }, + guild_id: guild_id, + } as GuildBanAddEvent); + + return res.json(ban).send(); +}); + +router.delete("/:user_id", async (req: Request, res: Response) => { + var { guild_id } = req.params; + var banned_user_id = req.params.user_id; + + const banned_user = await getPublicUser(banned_user_id); + const guild = await GuildModel.exists({ id: guild_id }); + if (!guild) throw new HTTPError("Guild not found", 404); + + const perms = await getPermission(req.user_id, guild_id); + if (!perms.has("BAN_MEMBERS")) { + throw new HTTPError("No permissions", 403); + } + + await BanModel.deleteOne({ + user_id: banned_user_id, + guild_id, + }).exec(); + + await emitEvent({ + event: "GUILD_BAN_REMOVE", + data: { + guild_id, + user: banned_user, + }, + guild_id, + } as GuildBanRemoveEvent); + + return res.status(204).send(); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/channels.ts b/src/routes/guilds/#guild_id/channels.ts new file mode 100644 index 00000000..e0d8f3ac --- /dev/null +++ b/src/routes/guilds/#guild_id/channels.ts @@ -0,0 +1,54 @@ +import { Router } from "express"; +import { ChannelCreateEvent, ChannelModel, ChannelType, GuildModel, Snowflake, toObject } from "fosscord-server-util"; +import { HTTPError } from "lambert-server"; +import { ChannelModifySchema } from "../../../schema/Channel"; +import { emitEvent } from "../../../util/Event"; +import { check } from "../../../util/instanceOf"; +const router = Router(); + +router.get("/", async (req, res) => { + const { guild_id } = req.params; + const channels = await ChannelModel.find({ guild_id }).exec(); + + res.json(toObject(channels)); +}); + +router.post("/", check(ChannelModifySchema), async (req, res) => { + const { guild_id } = req.params; + const body = req.body as ChannelModifySchema; + if (!body.permission_overwrites) body.permission_overwrites = []; + if (!body.topic) body.topic = ""; + if (!body.rate_limit_per_user) body.rate_limit_per_user = 0; + switch (body.type) { + case ChannelType.DM: + case ChannelType.GROUP_DM: + throw new HTTPError("You can't create a dm channel in a guild"); + // TODO: + case ChannelType.GUILD_STORE: + throw new HTTPError("Not yet supported"); + case ChannelType.GUILD_NEWS: + // TODO: check if guild is community server + } + + if (body.parent_id) { + const exists = ChannelModel.findOne({ channel_id: body.parent_id }).exec(); + if (!exists) throw new HTTPError("Parent id channel doesn't exist", 400); + } + + const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); + if (!guild) throw new HTTPError("Guild not found", 4040); + + const channel = { + ...body, + id: Snowflake.generate(), + created_at: new Date(), + guild_id, + }; + await new ChannelModel(channel).save(); + + await emitEvent({ event: "CHANNEL_CREATE", data: channel, guild_id } as ChannelCreateEvent); + + res.json(channel); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/index.ts b/src/routes/guilds/#guild_id/index.ts new file mode 100644 index 00000000..7e5f49d3 --- /dev/null +++ b/src/routes/guilds/#guild_id/index.ts @@ -0,0 +1,85 @@ +import { Request, Response, Router } from "express"; +import { + ChannelModel, + EmojiModel, + getPermission, + GuildDeleteEvent, + GuildModel, + GuildUpdateEvent, + InviteModel, + MemberModel, + MessageModel, + RoleModel, + toObject, + UserModel, +} from "fosscord-server-util"; +import { HTTPError } from "lambert-server"; +import { GuildUpdateSchema } from "../../../schema/Guild"; +import { emitEvent } from "../../../util/Event"; +import { check } from "../../../util/instanceOf"; +import "missing-native-js-functions"; + +const router = Router(); + +router.get("/", async (req: Request, res: Response) => { + const { guild_id } = req.params; + + const guild = await GuildModel.findOne({ id: guild_id }) + .populate({ path: "joined_at", match: { id: req.user_id } }) + .exec(); + if (!guild) throw new HTTPError("Guild does not exist", 404); + + const member = await MemberModel.exists({ 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); + + return res.json(guild); +}); + +router.patch("/", check(GuildUpdateSchema), async (req: Request, res: Response) => { + const body = req.body as GuildUpdateSchema; + const { guild_id } = req.params; + // TODO: guild update check image + + const perms = await getPermission(req.user_id, guild_id); + if (!perms.has("MANAGE_GUILD")) throw new HTTPError("You do not have the MANAGE_GUILD permission", 401); + + const guild = await GuildModel.findOneAndUpdate({ id: guild_id }, body) + .populate({ path: "joined_at", match: { id: req.user_id } }) + .exec(); + + const data = toObject(guild); + + emitEvent({ event: "GUILD_UPDATE", data: data, guild_id } as GuildUpdateEvent); + + return res.send(data); +}); + +// discord prefixes this route with /delete instead of using the delete method +// docs are wrong https://discord.com/developers/docs/resources/guild#delete-guild +router.post("/delete", async (req: Request, res: Response) => { + var { guild_id } = req.params; + + const guild = await GuildModel.findOne({ id: guild_id }, "owner_id").exec(); + if (!guild) throw new HTTPError("This guild does not exist", 404); + if (guild.owner_id !== req.user_id) throw new HTTPError("You are not the owner of this guild", 401); + + await emitEvent({ + event: "GUILD_DELETE", + data: { + id: guild_id, + }, + guild_id: guild_id, + } as GuildDeleteEvent); + + await GuildModel.deleteOne({ id: guild_id }).exec(); + await UserModel.updateMany({ guilds: guild_id }, { $pull: { guilds: guild_id } }).exec(); + await RoleModel.deleteMany({ guild_id }).exec(); + await ChannelModel.deleteMany({ guild_id }).exec(); + await EmojiModel.deleteMany({ guild_id }).exec(); + await InviteModel.deleteMany({ guild_id }).exec(); + await MessageModel.deleteMany({ guild_id }).exec(); + + return res.sendStatus(204); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/members.ts b/src/routes/guilds/#guild_id/members.ts new file mode 100644 index 00000000..f4e6d4e8 --- /dev/null +++ b/src/routes/guilds/#guild_id/members.ts @@ -0,0 +1,53 @@ +import { Request, Response, Router } from "express"; +import { GuildModel, MemberModel, toObject } from "fosscord-server-util"; +import { HTTPError } from "lambert-server"; +import { instanceOf, Length } from "../../../util/instanceOf"; +import { PublicMemberProjection } from "../../../util/Member"; +import { PublicUserProjection } from "../../../util/User"; + +const router = Router(); + +// TODO: not allowed for user -> only allowed for bots with privileged intents +// TODO: send over websocket +router.get("/", async (req: Request, res: Response) => { + const { guild_id } = req.params; + const guild = await GuildModel.findOne({ id: guild_id }).exec(); + if (!guild) throw new HTTPError("Guild not found", 404); + + try { + instanceOf({ $limit: new Length(Number, 1, 1000), $after: String }, req.query, { + path: "query", + req, + ref: { obj: null, key: "" }, + }); + } catch (error) { + return res.status(400).json({ code: 50035, message: "Invalid Query", success: false, errors: error }); + } + + // @ts-ignore + if (!req.query.limit) req.query.limit = 1; + const { limit, after } = (req.query) as { limit: number; after: string }; + const query = after ? { id: { $gt: after } } : {}; + + var members = await MemberModel.find({ guild_id, ...query }, PublicMemberProjection) + .limit(limit) + .exec(); + + return res.json(toObject(members)); +}); + +router.get("/:member", async (req: Request, res: Response) => { + const { guild_id } = req.params; + const user_id = req.params.member; + + const member = await MemberModel.findOne({ id: user_id, guild_id }).exec(); + if (!member) throw new HTTPError("Member not found", 404); + + return res.json(member); +}); + +router.put("/:member", async (req: Request, res: Response) => { + // https://discord.com/developers/docs/resources/guild#add-guild-member +}); + +export default router; diff --git a/src/routes/guilds/#id/bans.ts b/src/routes/guilds/#id/bans.ts deleted file mode 100644 index 5ac92154..00000000 --- a/src/routes/guilds/#id/bans.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { Request, Response, Router } from "express"; -import { BanModel, getPermission, GuildBanAddEvent, GuildBanRemoveEvent, GuildModel, toObject } from "fosscord-server-util"; -import { HTTPError } from "lambert-server"; -import { getIpAdress } from "../../../middlewares/GlobalRateLimit"; -import { BanCreateSchema } from "../../../schema/Ban"; -import { emitEvent } from "../../../util/Event"; -import { check } from "../../../util/instanceOf"; -import { removeMember } from "../../../util/Member"; -import { getPublicUser } from "../../../util/User"; - -const router: Router = Router(); - -router.get("/", async (req: Request, res: Response) => { - const guild_id = req.params.id; - - const guild = await GuildModel.findOne({ id: guild_id }).exec(); - if (!guild) throw new HTTPError("Guild not found", 404); - - var bans = await BanModel.find({ guild_id: guild_id }).exec(); - return res.json(toObject(bans)); -}); - -router.get("/:user", async (req: Request, res: Response) => { - const guild_id = req.params.id; - const user_id = req.params.ban; - - var ban = await BanModel.findOne({ guild_id: guild_id, user_id: user_id }).exec(); - if (!ban) throw new HTTPError("Ban not found", 404); - return res.json(ban); -}); - -router.post("/:user_id", check(BanCreateSchema), async (req: Request, res: Response) => { - const guild_id = req.params.id; - const banned_user_id = req.params.user_id; - - const banned_user = await getPublicUser(banned_user_id); - const perms = await getPermission(req.user_id, guild_id); - if (!perms.has("BAN_MEMBERS")) throw new HTTPError("You don't have the permission to ban members", 403); - if (req.user_id === banned_user_id) throw new HTTPError("You can't ban yourself", 400); - - await removeMember(banned_user_id, guild_id); - - const ban = await new BanModel({ - user_id: banned_user_id, - guild_id: guild_id, - ip: getIpAdress(req), - executor_id: req.user_id, - reason: req.body.reason, // || otherwise empty - }).save(); - - await emitEvent({ - event: "GUILD_BAN_ADD", - data: { - guild_id: guild_id, - user: banned_user, - }, - guild_id: guild_id, - } as GuildBanAddEvent); - - return res.json(ban).send(); -}); - -router.delete("/:user_id", async (req: Request, res: Response) => { - var guild_id = req.params.id; - var banned_user_id = req.params.user_id; - - const banned_user = await getPublicUser(banned_user_id); - const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); - if (!guild) throw new HTTPError("Guild not found", 404); - - const perms = await getPermission(req.user_id, guild.id); - if (!perms.has("BAN_MEMBERS")) { - throw new HTTPError("No permissions", 403); - } - - await BanModel.deleteOne({ - user_id: banned_user_id, - guild_id: guild.id, - }).exec(); - - await emitEvent({ - event: "GUILD_BAN_REMOVE", - data: { - guild_id: guild.id, - user: banned_user, - }, - guild_id: guild.id, - } as GuildBanRemoveEvent); - - return res.status(204).send(); -}); - -export default router; diff --git a/src/routes/guilds/#id/channels.ts b/src/routes/guilds/#id/channels.ts deleted file mode 100644 index b949def0..00000000 --- a/src/routes/guilds/#id/channels.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { Router } from "express"; -import { ChannelCreateEvent, ChannelModel, ChannelType, GuildModel, Snowflake, toObject } from "fosscord-server-util"; -import { HTTPError } from "lambert-server"; -import { ChannelModifySchema } from "../../../schema/Channel"; -import { emitEvent } from "../../../util/Event"; -import { check } from "../../../util/instanceOf"; -const router = Router(); - -router.get("/", async (req, res) => { - const guild_id = req.params.id; - const channels = await ChannelModel.find({ guild_id }).exec(); - - res.json(toObject(channels)); -}); - -router.post("/", check(ChannelModifySchema), async (req, res) => { - const guild_id = req.params.id; - const body = req.body as ChannelModifySchema; - if (!body.permission_overwrites) body.permission_overwrites = []; - if (!body.topic) body.topic = ""; - if (!body.rate_limit_per_user) body.rate_limit_per_user = 0; - switch (body.type) { - case ChannelType.DM: - case ChannelType.GROUP_DM: - throw new HTTPError("You can't create a dm channel in a guild"); - // TODO: - case ChannelType.GUILD_STORE: - throw new HTTPError("Not yet supported"); - case ChannelType.GUILD_NEWS: - // TODO: check if guild is community server - } - - if (body.parent_id) { - const exists = ChannelModel.findOne({ channel_id: body.parent_id }).exec(); - if (!exists) throw new HTTPError("Parent id channel doesn't exist", 400); - } - - const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); - if (!guild) throw new HTTPError("Guild not found", 4040); - - const channel = { - ...body, - id: Snowflake.generate(), - created_at: new Date(), - guild_id, - }; - await new ChannelModel(channel).save(); - - await emitEvent({ event: "CHANNEL_CREATE", data: channel, guild_id } as ChannelCreateEvent); - - res.json(channel); -}); - -export default router; diff --git a/src/routes/guilds/#id/index.ts b/src/routes/guilds/#id/index.ts deleted file mode 100644 index 385904f6..00000000 --- a/src/routes/guilds/#id/index.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { Request, Response, Router } from "express"; -import { - ChannelModel, - EmojiModel, - getPermission, - GuildDeleteEvent, - GuildModel, - InviteModel, - MemberModel, - MessageModel, - RoleModel, - UserModel, -} from "fosscord-server-util"; -import { HTTPError } from "lambert-server"; -import { GuildUpdateSchema } from "../../../schema/Guild"; -import { emitEvent } from "../../../util/Event"; -import { check } from "../../../util/instanceOf"; - -const router = Router(); - -router.get("/", async (req: Request, res: Response) => { - const guild_id = req.params.id; - - const guild = await GuildModel.findOne({ id: guild_id }).exec(); - if (!guild) throw new HTTPError("Guild does not exist", 404); - - const member = await MemberModel.findOne({ guild_id: guild_id, id: req.user_id }, "id").exec(); - if (!member) throw new HTTPError("You are not a member of the guild you are trying to access", 401); - - return res.json(guild); -}); - -router.patch("/", check(GuildUpdateSchema), async (req: Request, res: Response) => { - const body = req.body as GuildUpdateSchema; - const guild_id = req.params.id; - - const guild = await GuildModel.findOne({ id: guild_id }).exec(); - if (!guild) throw new HTTPError("This guild does not exist", 404); - - const perms = await getPermission(req.user_id, guild_id); - if (!perms.has("MANAGE_GUILD")) throw new HTTPError("You do not have the MANAGE_GUILD permission", 401); - - await GuildModel.updateOne({ id: guild_id }, body).exec(); - return res.status(204); -}); - -router.delete("/", async (req: Request, res: Response) => { - var guild_id = req.params.id; - - const guild = await GuildModel.findOne({ id: guild_id }, "owner_id").exec(); - if (!guild) throw new HTTPError("This guild does not exist", 404); - if (guild.owner_id !== req.user_id) throw new HTTPError("You are not the owner of this guild", 401); - - await emitEvent({ - event: "GUILD_DELETE", - data: { - id: guild_id, - }, - guild_id: guild_id, - } as GuildDeleteEvent); - - await GuildModel.deleteOne({ id: guild_id }).exec(); - await UserModel.updateMany({ guilds: guild_id }, { $pull: { guilds: guild_id } }).exec(); - await RoleModel.deleteMany({ guild_id }).exec(); - await ChannelModel.deleteMany({ guild_id }).exec(); - await EmojiModel.deleteMany({ guild_id }).exec(); - await InviteModel.deleteMany({ guild_id }).exec(); - await MessageModel.deleteMany({ guild_id }).exec(); - - return res.status(204).send(); -}); - -export default router; diff --git a/src/routes/guilds/#id/members.ts b/src/routes/guilds/#id/members.ts deleted file mode 100644 index 1c3cb33d..00000000 --- a/src/routes/guilds/#id/members.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { Request, Response, Router } from "express"; -import { GuildModel, MemberModel, toObject } from "fosscord-server-util"; -import { HTTPError } from "lambert-server"; -import { instanceOf, Length } from "../../../util/instanceOf"; -import { PublicMemberProjection } from "../../../util/Member"; -import { PublicUserProjection } from "../../../util/User"; - -const router = Router(); - -// TODO: not allowed for user -> only allowed for bots with privileged intents -// TODO: send over websocket -router.get("/", async (req: Request, res: Response) => { - const guild_id = req.params.id; - const guild = await GuildModel.findOne({ id: guild_id }).exec(); - if (!guild) throw new HTTPError("Guild not found", 404); - - try { - instanceOf({ $limit: new Length(Number, 1, 1000), $after: String }, req.query, { - path: "query", - req, - ref: { obj: null, key: "" }, - }); - } catch (error) { - return res.status(400).json({ code: 50035, message: "Invalid Query", success: false, errors: error }); - } - - // @ts-ignore - if (!req.query.limit) req.query.limit = 1; - const { limit, after } = (req.query) as { limit: number; after: string }; - const query = after ? { id: { $gt: after } } : {}; - - var members = await MemberModel.find({ guild_id, ...query }, PublicMemberProjection) - .limit(limit) - .populate({ path: "user", select: PublicUserProjection }) - .exec(); - - return res.json(toObject(members)); -}); - -router.get("/:member", async (req: Request, res: Response) => { - const guild_id = req.params.id; - const user_id = req.params.member; - - const member = await MemberModel.findOne({ id: user_id, guild_id }).populate({ path: "user", select: PublicUserProjection }).exec(); - if (!member) throw new HTTPError("Member not found", 404); - - return res.json(member); -}); - -router.put("/:member", async (req: Request, res: Response) => { - // https://discord.com/developers/docs/resources/guild#add-guild-member -}); - -export default router; diff --git a/src/routes/users/@me/guilds.ts b/src/routes/users/@me/guilds.ts index e04107ac..d0fbaa3e 100644 --- a/src/routes/users/@me/guilds.ts +++ b/src/routes/users/@me/guilds.ts @@ -11,37 +11,42 @@ router.get("/", async (req: Request, res: Response) => { if (!user) throw new HTTPError("User not found", 404); var guildIDs = user.guilds || []; - var guild = await GuildModel.find({ id: { $in: guildIDs } }).exec(); + var guild = await GuildModel.find({ id: { $in: guildIDs } }) + .populate({ path: "joined_at", match: { id: req.user_id } }) + .exec(); + res.json(toObject(guild)); }); // user send to leave a certain guild router.delete("/:id", async (req: Request, res: Response) => { - const guildID = req.params.id; - const guild = await GuildModel.findOne({ id: guildID }).exec(); + const guild_id = req.params.id; + const guild = await GuildModel.findOne({ id: guild_id }, { guild_id: true }).exec(); if (!guild) throw new HTTPError("Guild doesn't exist", 404); if (guild.owner_id === req.user_id) throw new HTTPError("You can't leave your own guild", 400); - await MemberModel.deleteOne({ id: req.user_id, guild_id: guildID }).exec(); - await UserModel.updateOne({ id: req.user_id }, { $pull: { guilds: guildID } }).exec(); - const user = await getPublicUser(req.user_id); + await Promise.all([ + MemberModel.deleteOne({ id: req.user_id, guild_id: guild_id }).exec(), + UserModel.updateOne({ id: req.user_id }, { $pull: { guilds: guild_id } }).exec(), + emitEvent({ + event: "GUILD_DELETE", + data: { + id: guild_id, + }, + user_id: req.user_id, + } as GuildDeleteEvent), + ]); - await emitEvent({ - event: "GUILD_DELETE", - data: { - id: guildID, - }, - user_id: req.user_id, - } as GuildDeleteEvent); + const user = await getPublicUser(req.user_id); await emitEvent({ event: "GUILD_MEMBER_REMOVE", data: { - guild_id: guildID, + guild_id: guild_id, user: user, }, - guild_id: guildID, + guild_id: guild_id, } as GuildMemberRemoveEvent); return res.status(204).send(); diff --git a/src/util/Event.ts b/src/util/Event.ts index 43c51d5c..8a24e4bb 100644 --- a/src/util/Event.ts +++ b/src/util/Event.ts @@ -5,6 +5,7 @@ export async function emitEvent(payload: Omit) { created_at: new Date(), // in seconds ...payload, }; + // TODO: bigint isn't working return await new EventModel(obj).save(); } diff --git a/src/util/Member.ts b/src/util/Member.ts index 3ce06962..4d1b8ac5 100644 --- a/src/util/Member.ts +++ b/src/util/Member.ts @@ -75,6 +75,7 @@ export async function addMember(user_id: string, guild_id: string, cache?: { gui }, guild_id: guild_id, } as GuildMemberAddEvent), + emitEvent({ event: "GUILD_CREATE", data: guild, -- cgit 1.5.1