|
| 1 | +import type { RequestHandler } from './$types'; |
| 2 | +import { config } from 'config'; |
| 3 | +import { env } from '$env/dynamic/private'; |
| 4 | +import { logger } from '$lib/logger'; |
| 5 | +import { BotResult } from '$lib/DiscordTypes'; |
| 6 | + |
| 7 | +enum MemberResult { |
| 8 | + Found, |
| 9 | + NotFound, |
| 10 | + Error |
| 11 | +} |
| 12 | + |
| 13 | +async function getGuildMember(id: string) { |
| 14 | + try { |
| 15 | + const response = await fetch(`https://discord.com/api/v10/guilds/${config.discord.guildId}/members/${id}`, { |
| 16 | + method: 'GET', |
| 17 | + headers: { |
| 18 | + "Content-Type": "application/json", |
| 19 | + "Authorization": `Bot ${env.DISCORD_BOT_TOKEN}` |
| 20 | + }, |
| 21 | + }); |
| 22 | + |
| 23 | + const json = await response.json(); |
| 24 | + switch (response.status) { |
| 25 | + case 200: |
| 26 | + return { content: json, result: MemberResult.Found } as const; |
| 27 | + case 404: |
| 28 | + logger.info(`User ${id} not found in guild.`); |
| 29 | + return { content: json, result: MemberResult.NotFound } as const; |
| 30 | + default: |
| 31 | + logger.error(`Error checking if user ${id} exists in guild: ${response.status}: ${response.statusText}`); |
| 32 | + return { content: json, result: MemberResult.Error } as const; |
| 33 | + } |
| 34 | + } catch (e) { |
| 35 | + logger.error(e); |
| 36 | + return { content: { code: -5000, message: 'Network error' }, result: MemberResult.Error } as const; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +async function joinDiscordServer(userId: string, accessToken: string, nickname: string) { |
| 41 | + try { |
| 42 | + const response = await fetch(`https://discord.com/api/v10/guilds/${config.discord.guildId}/members/${userId}`, { |
| 43 | + body: JSON.stringify({ |
| 44 | + access_token: accessToken, |
| 45 | + nick: nickname, |
| 46 | + roles: config.discord.roles.map((val) => val.id) |
| 47 | + }), |
| 48 | + method: 'PUT', |
| 49 | + headers: { |
| 50 | + "Content-Type": "application/json", |
| 51 | + "Authorization": `Bot ${env.DISCORD_BOT_TOKEN}` |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + switch (response.status) { |
| 56 | + case 201: |
| 57 | + case 204: |
| 58 | + return { result: BotResult.Success, error: null } as const; |
| 59 | + case 400: |
| 60 | + return { result: BotResult.Full, error: await response.json() } as const; |
| 61 | + default: |
| 62 | + return { result: BotResult.Error, error: await response.json() } as const; |
| 63 | + } |
| 64 | + } catch (e) { |
| 65 | + logger.error(e); |
| 66 | + return { result: BotResult.Error, error: { code: -5000, message: 'Network Error' } } as const; |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +async function addRoleToUser(userId: string, roles: string[], nick: string) { |
| 71 | + const response = await fetch(`https://discord.com/api/v10/guilds/${config.discord.guildId}/members/${userId}`, { |
| 72 | + body: JSON.stringify({ nick, roles }), |
| 73 | + method: 'PATCH', |
| 74 | + headers: { |
| 75 | + "Content-Type": "application/json", |
| 76 | + "Authorization": `Bot ${env.DISCORD_BOT_TOKEN}` |
| 77 | + }, |
| 78 | + }); |
| 79 | + |
| 80 | + switch (response.status) { |
| 81 | + case 200: |
| 82 | + case 204: |
| 83 | + return { result: BotResult.Success, error: null } as const; |
| 84 | + default: |
| 85 | + return { result: BotResult.Error, error: await response.json() } as const; |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +export const POST = (async ({ locals }) => { |
| 90 | + const discordId = locals.session.data.discord?.id; |
| 91 | + const accessToken = locals.session.data.discord?.accessToken; |
| 92 | + const osuUsername = locals.session.data.osu?.username ?? ''; |
| 93 | + |
| 94 | + if (!discordId || !accessToken) { |
| 95 | + return new Response(JSON.stringify({ result: 'error', message: 'Missing session data.' }), { status: 400 }); |
| 96 | + } |
| 97 | + |
| 98 | + const memberCheck = await getGuildMember(discordId); |
| 99 | + if (memberCheck.result === MemberResult.Found) { |
| 100 | + logger.info(`User ${discordId} already exists in the guild. Adding roles...`); |
| 101 | + const requiredRoles = config.discord.roles.map((val) => val.id); |
| 102 | + const guildMember = memberCheck.content as { roles: string[] }; |
| 103 | + const mergedRoles = Array.from(new Set([...(guildMember.roles || []), ...requiredRoles])); |
| 104 | + const unchanged = mergedRoles.length === (guildMember.roles || []).length && (guildMember.roles || []).every((id: string) => mergedRoles.includes(id)); |
| 105 | + if (unchanged) { |
| 106 | + await locals.session.update((d) => { (d as any).isReady = true; return d; }); |
| 107 | + return new Response(JSON.stringify({ result: 'success' })); |
| 108 | + } |
| 109 | + const addRoleRes = await addRoleToUser(discordId, requiredRoles, osuUsername); |
| 110 | + if (addRoleRes.result === BotResult.Success) { |
| 111 | + await locals.session.update((d) => { (d as any).isReady = true; return d; }); |
| 112 | + return new Response(JSON.stringify({ result: 'success' })); |
| 113 | + } |
| 114 | + return new Response(JSON.stringify({ result: 'error', message: addRoleRes.error?.message || 'Failed adding roles' }), { status: 500 }); |
| 115 | + } |
| 116 | + |
| 117 | + if (memberCheck.result === MemberResult.NotFound) { |
| 118 | + const joinRes = await joinDiscordServer(discordId, accessToken, osuUsername); |
| 119 | + if (joinRes.result === BotResult.Full) { |
| 120 | + await locals.session.update((d) => { d.error = 'You have joined the maximum amount of servers.'; return d; }); |
| 121 | + return new Response(JSON.stringify({ result: 'full' }), { status: 200 }); |
| 122 | + } |
| 123 | + if (joinRes.result !== BotResult.Success) { |
| 124 | + return new Response(JSON.stringify({ result: 'error', message: joinRes.error?.message || 'Failed to join server' }), { status: 500 }); |
| 125 | + } |
| 126 | + const requiredRoles = config.discord.roles.map((val) => val.id); |
| 127 | + const addRoleRes = await addRoleToUser(discordId, requiredRoles, osuUsername); |
| 128 | + if (addRoleRes.result === BotResult.Success) { |
| 129 | + await locals.session.update((d) => { (d as any).isReady = true; return d; }); |
| 130 | + return new Response(JSON.stringify({ result: 'success' })); |
| 131 | + } |
| 132 | + return new Response(JSON.stringify({ result: 'error', message: addRoleRes.error?.message || 'Failed adding roles' }), { status: 500 }); |
| 133 | + } |
| 134 | + |
| 135 | + return new Response(JSON.stringify({ result: 'error', message: 'Discord API error' }), { status: 502 }); |
| 136 | +}) satisfies RequestHandler; |
| 137 | + |
| 138 | + |
0 commit comments