all repos — stealth-developers @ e3649499a4f2c6f95902a43a0f171e9df0d40ad1

apps/api/src/routes/sync.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
import config from "@stealth-developers/config";
import { editActor, getActorByPin, getActorByRobloxId, getToken } from "@stealth-developers/db";
import Elysia, { type Static, t } from "elysia";

import { generateWidget } from "@/lib/widgets/meow";

const syncPushResponseItem = t.Union([
	t.Object(
		{
			user_id: t.String(),
			success: t.Literal(true),
		},
		{ title: "SyncPushResponseItemSuccess" },
	),
	t.Object(
		{
			user_id: t.String(),
			success: t.Literal(false),
			error: t.String(),
		},
		{ title: "SyncPushResponseItemError" },
	),
]);
const syncPushResponse = t.Array(syncPushResponseItem);

export type SyncPushResponseItem = Static<typeof syncPushResponseItem>;
export type SyncPushResponse = Static<typeof syncPushResponse>;

export const syncRoutes = new Elysia({ prefix: "/sync" })
	.resolve(async ({ request }) => {
		const auth = request.headers.get("Authorization");
		const tokenString = auth?.split(" ")[1];
		if (!tokenString)
			throw new Error("Found no token, note that it must be prefixed with `Bearer`");

		const token = await getToken(tokenString);
		if (!token) throw new Error("Invalid token");

		return { token };
	})
	.post(
		"/verify",
		async ({ body, set }) => {
			const user = await getActorByPin(body.pin);
			if (!user) {
				set.status = 404;
				return { error: "Pin not found" };
			}

			const expiryDate = new Date(user.pinExpiresIn!);
			if (expiryDate < new Date()) {
				set.status = 401;
				return { error: "Pin expired" };
			}

			await editActor(user.id, {
				robloxId: body.roblox_user_id,
				pin: null,
				pinExpiresIn: null,
			});

			return { success: true };
		},
		{
			tags: ["widgets"],
			body: t.Object({
				pin: t.String(),
				roblox_user_id: t.String(),
			}),
			response: {
				200: t.Object({
					success: t.Boolean(),
				}),
				401: t.Object({
					error: t.String(),
				}),
				404: t.Object({
					error: t.String(),
				}),
			},
		},
	)
	.post(
		"/push",
		async ({ body, set }) => {
			const results: SyncPushResponse = [];
			for (const user of body) {
				try {
					const actor = await getActorByRobloxId(user.user_id);
					if (!actor) {
						results.push({
							user_id: user.user_id,
							success: false,
							error: "User not found",
						});
						continue;
					}

					const discordId = actor.discordId;
					if (!discordId) {
						results.push({
							user_id: user.user_id,
							success: false,
							error: "Discord ID not found",
						});
						continue;
					}

					const widget = generateWidget({
						kills: String(user.kills),
						deaths: String(user.deaths),
						matchesWon: String(user.wins),
						level: String(user.level),
					});

					const response = await fetch(
						`https://discord.com/api/v10/applications/${config.discord.app_id}/users/${discordId}/identities/${user.user_id}/profile`,
						{
							method: "PATCH",
							headers: {
								Authorization: `Bot ${config.discord.token}`,
								"Content-Type": "application/json",
							},
							body: JSON.stringify(widget),
						},
					);

					if (!response.ok) {
						const errorText = await response.text();
						console.error(
							`Discord API Error for ${user.user_id}: ${response.status} - ${errorText}`,
						);
						results.push({
							user_id: user.user_id,
							success: false,
							error: `Discord API Error: ${response.status}`,
						});
						continue;
					}

					results.push({
						user_id: user.user_id,
						success: true,
					});
				} catch (error) {
					console.error(`Unexpected error processing user ${user.user_id}:`, error);
					results.push({
						user_id: user.user_id,
						success: false,
						error: error instanceof Error ? error.message : "Internal Server Error",
					});
				}
			}

			const hasFailures = results.some((r) => !r.success);
			const hasSuccesses = results.some((r) => r.success);

			if (!hasFailures) set.status = 200;
			else if (hasSuccesses) set.status = 207;
			else set.status = 400;

			return results;
		},
		{
			tags: ["widgets"],
			body: t.Array(
				t.Object({
					user_id: t.String(),
					kills: t.Number(),
					deaths: t.Number(),
					wins: t.Number(),
					level: t.Number(),
				}),
			),
			response: {
				200: syncPushResponse,
				207: syncPushResponse,
				400: syncPushResponse,
			},
		},
	);