-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
206 lines (188 loc) · 7.12 KB
/
Copy pathutils.ts
File metadata and controls
206 lines (188 loc) · 7.12 KB
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { REST } from "@discordjs/rest";
import {
APIApplicationCommandInteraction,
APIChatInputApplicationCommandInteraction,
APIDMChannel,
APIInteraction,
APIInteractionResponse,
APIInteractionResponseCallbackData,
APIMessageComponentInteraction,
APIModalSubmitInteraction,
ApplicationCommandType,
InteractionResponseType,
InteractionType,
Routes,
} from "discord-api-types/v10";
import { generateSnowflake } from "./snowflake";
import { DrizzleDB, SupportedPlatforms } from "../types";
import { users } from "./db/schema";
import { eq } from "drizzle-orm";
import { Colors } from "honocord";
import { GetSupportedPlatform } from "./constants";
export class JsonResponse extends Response {
constructor(body: any, init?: ResponseInit) {
const jsonBody = JSON.stringify(body);
init = init || {
headers: {
"content-type": "application/json;charset=UTF-8",
},
};
super(jsonBody, init);
}
}
export class APIResponse extends JsonResponse {
constructor(data: APIInteractionResponse, init?: ResponseInit) {
super(data, init);
}
}
/**
* A generic function to send a message response to Discord interactions.
*
* @param data The message content or response data to send.
* @param forceEphemeral Whether to force the message to be ephemeral (only visible to the user).
* @returns An APIResponse object containing the interaction response.
*/
export function sendMessage(data: APIInteractionResponseCallbackData | string, forceEphemeral = true) {
return new APIResponse({
type: InteractionResponseType.ChannelMessageWithSource,
data: {
...(typeof data === "string" ? { content: data } : data),
flags: forceEphemeral && typeof data !== "string" ? (data.flags || 0) | 64 : typeof data === "string" ? 0 : data.flags,
},
});
}
// Typeguards because TypeScript is bad at narrowing unions
export function isChatInputCommandInteraction(
interaction: APIApplicationCommandInteraction,
): interaction is APIChatInputApplicationCommandInteraction {
return interaction.data.type === ApplicationCommandType.ChatInput;
}
export function isModalInteraction(interaction: APIInteraction): interaction is APIModalSubmitInteraction {
return interaction.type === InteractionType.ModalSubmit;
}
export function isMessageComponentInteraction(interaction: APIInteraction): interaction is APIMessageComponentInteraction {
return interaction.type === InteractionType.MessageComponent;
}
export function randomStringWithSnowflake(length: number) {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._+=!@";
// The snowflake ensures uniqueness across calls
return (
Array.from({ length })
.map(() => chars.charAt(Math.floor(Math.random() * chars.length)))
.join("") + generateSnowflake().toString()
);
}
/**
* An array of delay intervals for retrying operations, used for exponential backoff.
*
* ```[0, 30, 60, 120, 300, 600, 1800, 3600]```
*/
export const delaySeconds = [0, 30, 60, 120, 300, 600, 1800, 3600]; // in seconds; we start at 0, because first attempt has number 1
/**
* Calculates a delay with added jitter to prevent thundering herd problems.
*
* @param baseDelay - The base delay time in milliseconds
* @param jitterFactor - A multiplier (0-1) that determines the maximum jitter as a fraction of baseDelay
* @returns The calculated delay with jitter applied, rounded down to the nearest integer
*
* @example
* ```typescript
* // Add up to 10% jitter to a 10s base delay
* const delay = jitterDelay(10, 0.1); // Returns 10-11s
* ```
*/
export const jitterDelay = (baseDelay: number, jitterFactor: number) => {
const jitter = Math.random() * jitterFactor * baseDelay;
return Math.floor(baseDelay + jitter);
};
/**
* Sanitizes a secret string by masking the the characters after the first four with asterisks.
*
* @param secret - The secret string to sanitize
* @returns The sanitized secret string
*/
export function sanitizeSecret(secret: string) {
return secret.slice(0, 4) + "*".repeat(Math.max(0, secret.length - 4));
}
export async function dmUserOnTestVote(
db: DrizzleDB,
env: Env,
{ userId, applicationId, source }: { userId: string; applicationId: string; source: SupportedPlatforms },
) {
console.log(`Starting DM process for test vote - userId: ${userId}, applicationId: ${applicationId}, source: ${source}`);
const rest = new REST({ version: "10" }).setToken(env.DISCORD_TOKEN);
const existingUserDM = await db.select({ dmId: users.dmId }).from(users).where(eq(users.id, userId)).limit(1).get();
console.log(`Existing DM check result:`, existingUserDM);
let dmChannelId: string;
if (existingUserDM?.dmId) {
dmChannelId = existingUserDM.dmId;
console.log(`Using existing DM channel: ${dmChannelId}`);
} else {
console.log(`Creating new DM channel for user: ${userId}`);
try {
const response = await rest.post(Routes.userChannels(), {
body: {
recipient_id: userId,
},
signal: AbortSignal.timeout(5000),
});
const dmChannel = response as APIDMChannel;
dmChannelId = dmChannel.id;
await db
.insert(users)
.values({ id: userId, dmId: dmChannelId })
.onConflictDoUpdate({
target: users.id,
set: { dmId: dmChannelId },
});
console.log(`Created new DM channel: ${dmChannelId}`);
} catch (error) {
console.error("Failed to create DM channel for test vote:", { error, userId });
return;
}
}
console.log(`Sending test vote notification to DM channel: ${dmChannelId}`);
try {
await rest.post(Routes.channelMessages(dmChannelId), {
body: {
embeds: [
{
title: "Test Vote Received",
description: `We received your test vote for <@${applicationId}> (${applicationId}) on platform \`${GetSupportedPlatform(
source,
)}\`.\nNo roles or rewards have been applied.`,
color: Colors.Blurple,
timestamp: new Date().toISOString(),
},
],
},
});
console.log(`Successfully sent test vote notification to user: ${userId}`);
} catch (error) {
console.error("Failed to send DM for test vote:", { error, userId, dmChannelId });
return;
}
}
/**
* Cleans a URL by removing query parameters and hash fragments, leaving only the base URL.
* @param url The URL to clean
* @returns The cleaned URL without query parameters or hash fragments
*/
export function cleanUrl(url: string) {
try {
const parsedUrl = new URL(url);
parsedUrl.search = "";
parsedUrl.hash = "";
return parsedUrl.toString();
} catch (error) {
console.error("Invalid URL provided to cleanUrl:", { url, error });
return url; // Return the original URL if parsing fails
}
}
export function getAuthorizeUrlForOwnershipVerify(requestUrl: string, botId: string) {
const redirectUri = new URL(requestUrl);
redirectUri.pathname = `/ownership-verify`;
redirectUri.search = "";
redirectUri.hash = "";
return `https://discord.com/api/oauth2/authorize?client_id=${botId}&scope=applications.entitlements+identify&redirect_uri=${encodeURIComponent(redirectUri.toString())}&response_type=code`;
}