Spaces:
Paused
Paused
Update src/router.js
Browse files- src/router.js +128 -11
src/router.js
CHANGED
|
@@ -4,7 +4,8 @@ import { generateWelcomeCard } from './canvas/welcomeCard.js';
|
|
| 4 |
import { generateLeaveCard } from './canvas/leaveCard.js';
|
| 5 |
|
| 6 |
// Import global proxy handler
|
| 7 |
-
import { patchWebhook } from './utils/proxy.js';
|
|
|
|
| 8 |
|
| 9 |
// Import command handlers
|
| 10 |
import handleSetup from './commands/setup.js';
|
|
@@ -81,17 +82,13 @@ export default async function router(req, res, pathname, body) {
|
|
| 81 |
if (pathname === '/interactions' && req.method === 'POST') {
|
| 82 |
res.setHeader('Content-Type', 'application/json');
|
| 83 |
|
| 84 |
-
// Validate API secret coming from outbound sources
|
| 85 |
const secret = process.env.API_SECRET;
|
| 86 |
if (!secret || req.headers['x-api-secret'] !== secret) {
|
| 87 |
res.writeHead(401);
|
| 88 |
return res.end(JSON.stringify({ error: 'Unauthorized' }));
|
| 89 |
}
|
| 90 |
|
| 91 |
-
// Parse body context safely
|
| 92 |
const interaction = typeof body === 'string' ? JSON.parse(body) : body;
|
| 93 |
-
|
| 94 |
-
// Get command name and route to handler
|
| 95 |
const commandName = interaction.data?.name;
|
| 96 |
const handler = COMMAND_HANDLERS[commandName];
|
| 97 |
|
|
@@ -168,7 +165,6 @@ export default async function router(req, res, pathname, body) {
|
|
| 168 |
if (pathname === '/internal/guilds' && req.method === 'GET') {
|
| 169 |
res.setHeader('Content-Type', 'application/json');
|
| 170 |
|
| 171 |
-
// Validate secret header injected by the Discloud bot framework
|
| 172 |
const secret = process.env.API_SECRET;
|
| 173 |
if (!secret || req.headers['x-api-secret'] !== secret) {
|
| 174 |
res.writeHead(401);
|
|
@@ -178,13 +174,10 @@ export default async function router(req, res, pathname, body) {
|
|
| 178 |
try {
|
| 179 |
console.log('[Sync Node] Fetching all server configurations from storage layer...');
|
| 180 |
|
| 181 |
-
// Pull configurations from your JSON storage file via your hfClient layout
|
| 182 |
-
// Note: If your saved configs file uses a different name than 'guilds.json' (e.g. 'configs.json'), update it below
|
| 183 |
const configurations = await getCached('all-guild-configs', () =>
|
| 184 |
readJSON('guilds.json').catch(() => [])
|
| 185 |
);
|
| 186 |
|
| 187 |
-
// Your Python bot expects an iterable JSON list array containing objects with a 'guildId'
|
| 188 |
const rawPayload = Array.isArray(configurations) ? configurations : Object.values(configurations);
|
| 189 |
|
| 190 |
res.writeHead(200);
|
|
@@ -195,15 +188,139 @@ export default async function router(req, res, pathname, body) {
|
|
| 195 |
return res.end(JSON.stringify({ error: 'Failed to extract system config trees', details: err.message }));
|
| 196 |
}
|
| 197 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
//
|
| 200 |
if (pathname === '/health' && req.method === 'GET') {
|
| 201 |
res.setHeader('Content-Type', 'application/json');
|
| 202 |
res.writeHead(200);
|
| 203 |
return res.end(JSON.stringify({ status: 'ok' }));
|
| 204 |
}
|
| 205 |
|
| 206 |
-
//
|
| 207 |
res.setHeader('Content-Type', 'application/json');
|
| 208 |
res.writeHead(404);
|
| 209 |
return res.end(JSON.stringify({ error: 'Not Found' }));
|
|
|
|
| 4 |
import { generateLeaveCard } from './canvas/leaveCard.js';
|
| 5 |
|
| 6 |
// Import global proxy handler
|
| 7 |
+
import { patchWebhook, fetchViaProxy } from './utils/proxy.js';
|
| 8 |
+
import { parseTemplate } from './utils/templateParser.js';
|
| 9 |
|
| 10 |
// Import command handlers
|
| 11 |
import handleSetup from './commands/setup.js';
|
|
|
|
| 82 |
if (pathname === '/interactions' && req.method === 'POST') {
|
| 83 |
res.setHeader('Content-Type', 'application/json');
|
| 84 |
|
|
|
|
| 85 |
const secret = process.env.API_SECRET;
|
| 86 |
if (!secret || req.headers['x-api-secret'] !== secret) {
|
| 87 |
res.writeHead(401);
|
| 88 |
return res.end(JSON.stringify({ error: 'Unauthorized' }));
|
| 89 |
}
|
| 90 |
|
|
|
|
| 91 |
const interaction = typeof body === 'string' ? JSON.parse(body) : body;
|
|
|
|
|
|
|
| 92 |
const commandName = interaction.data?.name;
|
| 93 |
const handler = COMMAND_HANDLERS[commandName];
|
| 94 |
|
|
|
|
| 165 |
if (pathname === '/internal/guilds' && req.method === 'GET') {
|
| 166 |
res.setHeader('Content-Type', 'application/json');
|
| 167 |
|
|
|
|
| 168 |
const secret = process.env.API_SECRET;
|
| 169 |
if (!secret || req.headers['x-api-secret'] !== secret) {
|
| 170 |
res.writeHead(401);
|
|
|
|
| 174 |
try {
|
| 175 |
console.log('[Sync Node] Fetching all server configurations from storage layer...');
|
| 176 |
|
|
|
|
|
|
|
| 177 |
const configurations = await getCached('all-guild-configs', () =>
|
| 178 |
readJSON('guilds.json').catch(() => [])
|
| 179 |
);
|
| 180 |
|
|
|
|
| 181 |
const rawPayload = Array.isArray(configurations) ? configurations : Object.values(configurations);
|
| 182 |
|
| 183 |
res.writeHead(200);
|
|
|
|
| 188 |
return res.end(JSON.stringify({ error: 'Failed to extract system config trees', details: err.message }));
|
| 189 |
}
|
| 190 |
}
|
| 191 |
+
|
| 192 |
+
// 6. POST /internal/member-event - Called by Discloud bot on member join/leave
|
| 193 |
+
if (pathname === '/internal/member-event' && req.method === 'POST') {
|
| 194 |
+
res.setHeader('Content-Type', 'application/json');
|
| 195 |
+
|
| 196 |
+
const secret = process.env.API_SECRET;
|
| 197 |
+
if (!secret || req.headers['x-api-secret'] !== secret) {
|
| 198 |
+
res.writeHead(401);
|
| 199 |
+
return res.end(JSON.stringify({ error: 'Unauthorized' }));
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
const { event, guildId, userId, username, globalName, avatarUrl, memberCount } = body || {};
|
| 203 |
+
|
| 204 |
+
if (!event || !guildId || !userId) {
|
| 205 |
+
res.writeHead(400);
|
| 206 |
+
return res.end(JSON.stringify({ error: 'Missing required fields: event, guildId, userId' }));
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
console.log(`[Member Event] '${event}' for ${username} (${userId}) in guild ${guildId}`);
|
| 210 |
+
|
| 211 |
+
try {
|
| 212 |
+
// Load this guild's config from HF bucket storage (same path all commands use)
|
| 213 |
+
const config = await readJSON(`guilds/${guildId}/config.json`);
|
| 214 |
+
|
| 215 |
+
if (!config) {
|
| 216 |
+
console.log(`[Member Event] No config for guild ${guildId} — ignoring.`);
|
| 217 |
+
res.writeHead(200);
|
| 218 |
+
return res.end(JSON.stringify({ status: 'no_config' }));
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
const isJoin = event === 'join';
|
| 222 |
+
const channelId = isJoin ? config.welcomeChannelId : config.leaveChannelId;
|
| 223 |
+
|
| 224 |
+
if (!channelId) {
|
| 225 |
+
console.log(`[Member Event] Guild ${guildId} has no ${isJoin ? 'welcome' : 'leave'} channel set.`);
|
| 226 |
+
res.writeHead(200);
|
| 227 |
+
return res.end(JSON.stringify({ status: 'no_channel' }));
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
// Fetch guild name via proxy mesh (same pattern as preview.js)
|
| 231 |
+
let guildName = 'Unknown Server';
|
| 232 |
+
try {
|
| 233 |
+
const guildResponse = await fetchViaProxy(`/v10/guilds/${guildId}?with_counts=true`, {
|
| 234 |
+
method: 'GET',
|
| 235 |
+
headers: { 'Authorization': `Bot ${process.env.DISCORD_BOT_TOKEN}` }
|
| 236 |
+
});
|
| 237 |
+
if (guildResponse.ok) {
|
| 238 |
+
const guildData = await guildResponse.json();
|
| 239 |
+
guildName = guildData.name || guildName;
|
| 240 |
+
}
|
| 241 |
+
} catch (err) {
|
| 242 |
+
console.warn(`[Member Event] Could not fetch guild name, using fallback: ${err.message}`);
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
// Build the card image using the exact same generators the /generate routes use
|
| 246 |
+
const displayName = globalName || username;
|
| 247 |
+
const cardAvatarUrl = avatarUrl || `https://cdn.discordapp.com/embed/avatars/0.png`;
|
| 248 |
+
|
| 249 |
+
const imageBuffer = isJoin
|
| 250 |
+
? await generateWelcomeCard({
|
| 251 |
+
avatarURL: cardAvatarUrl,
|
| 252 |
+
username: displayName,
|
| 253 |
+
serverName: guildName,
|
| 254 |
+
memberCount: memberCount,
|
| 255 |
+
config: config,
|
| 256 |
+
guildId: guildId
|
| 257 |
+
})
|
| 258 |
+
: await generateLeaveCard({
|
| 259 |
+
avatarURL: cardAvatarUrl,
|
| 260 |
+
username: displayName,
|
| 261 |
+
serverName: guildName,
|
| 262 |
+
memberCount: memberCount,
|
| 263 |
+
config: config,
|
| 264 |
+
guildId: guildId
|
| 265 |
+
});
|
| 266 |
+
|
| 267 |
+
// Parse the text message template using existing templateParser
|
| 268 |
+
// templateParser supports: {username} {server} {memberCount}
|
| 269 |
+
const rawTemplate = isJoin ? config.welcomeMessage : config.leaveMessage;
|
| 270 |
+
const messageText = parseTemplate(rawTemplate, {
|
| 271 |
+
username: displayName,
|
| 272 |
+
server: guildName,
|
| 273 |
+
memberCount: String(memberCount ?? '')
|
| 274 |
+
});
|
| 275 |
+
|
| 276 |
+
// Send card image + text message to the channel via proxy mesh
|
| 277 |
+
// Uses multipart/form-data with payload_json + file attachment (same shape as patchWebhook with file)
|
| 278 |
+
const formData = new FormData();
|
| 279 |
+
const payload = {
|
| 280 |
+
content: messageText || undefined,
|
| 281 |
+
embeds: [{
|
| 282 |
+
color: isJoin ? 0x57F287 : 0xED4245,
|
| 283 |
+
image: { url: 'attachment://card.png' },
|
| 284 |
+
timestamp: new Date().toISOString()
|
| 285 |
+
}]
|
| 286 |
+
};
|
| 287 |
+
formData.append('payload_json', JSON.stringify(payload));
|
| 288 |
+
formData.append('files[0]', new Blob([imageBuffer], { type: 'image/png' }), 'card.png');
|
| 289 |
+
|
| 290 |
+
const sendResponse = await fetchViaProxy(`/v10/channels/${channelId}/messages`, {
|
| 291 |
+
method: 'POST',
|
| 292 |
+
headers: {
|
| 293 |
+
'Authorization': `Bot ${process.env.DISCORD_BOT_TOKEN}`
|
| 294 |
+
},
|
| 295 |
+
body: formData
|
| 296 |
+
});
|
| 297 |
+
|
| 298 |
+
if (sendResponse.ok) {
|
| 299 |
+
console.log(`[Member Event] ✅ Card sent to channel ${channelId} for '${event}' event`);
|
| 300 |
+
res.writeHead(200);
|
| 301 |
+
return res.end(JSON.stringify({ status: 'sent' }));
|
| 302 |
+
} else {
|
| 303 |
+
const errText = await sendResponse.text().catch(() => '');
|
| 304 |
+
console.error(`[Member Event] Discord returned ${sendResponse.status}: ${errText}`);
|
| 305 |
+
res.writeHead(502);
|
| 306 |
+
return res.end(JSON.stringify({ status: 'discord_error', code: sendResponse.status, detail: errText }));
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
} catch (err) {
|
| 310 |
+
console.error(`[Member Event Fatal] ${err.message}`, err);
|
| 311 |
+
res.writeHead(500);
|
| 312 |
+
return res.end(JSON.stringify({ error: err.message }));
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
|
| 316 |
+
// 7. GET /health
|
| 317 |
if (pathname === '/health' && req.method === 'GET') {
|
| 318 |
res.setHeader('Content-Type', 'application/json');
|
| 319 |
res.writeHead(200);
|
| 320 |
return res.end(JSON.stringify({ status: 'ok' }));
|
| 321 |
}
|
| 322 |
|
| 323 |
+
// 8. 404 for unmatched routes
|
| 324 |
res.setHeader('Content-Type', 'application/json');
|
| 325 |
res.writeHead(404);
|
| 326 |
return res.end(JSON.stringify({ error: 'Not Found' }));
|