Brozy123 commited on
Commit
1788076
·
verified ·
1 Parent(s): 9c11be6

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +41 -10
server.js CHANGED
@@ -78,7 +78,11 @@ function hasDashboardPermissions(permissionBits) {
78
  function getRedirectUri() {
79
  if (REDIRECT_URI) return REDIRECT_URI;
80
  const spaceId = process.env.SPACE_ID;
81
- if (spaceId) return `https://${spaceId.replace('/', '-').toLowerCase()}.hf.space/callback`;
 
 
 
 
82
  return `http://localhost:${port}/callback`;
83
  }
84
 
@@ -114,6 +118,11 @@ app.use((req, res, next) => {
114
 
115
  // --- Static Assets ---
116
  app.get('/', (req, res) => {
 
 
 
 
 
117
  res.sendFile(path.join(__dirname, 'dashboard.html'));
118
  });
119
  app.get('/logo.png', (req, res) => {
@@ -145,21 +154,34 @@ app.get('/auth/login', (req, res) => {
145
 
146
  async function fetchWithRetry(url, options, retries = 2) {
147
  for (let i = 0; i <= retries; i++) {
 
 
 
148
  try {
149
  let targetUrl = url;
150
- // Use direct connection to Discord API
151
  if (url.includes('discord.com/api')) {
152
- targetUrl = url; // Keep direct connection - no endpoint rotation
153
  if (i > 0) console.log(`[Dashboard] Retrying Discord API call (${i + 1}/${retries})...`);
154
  }
155
 
156
- const res = await fetch(targetUrl, options);
157
- if (!res.ok && i < retries) throw new Error(`HTTP ${res.status}`);
 
 
 
 
 
 
 
 
 
158
  return res;
159
  } catch (err) {
 
160
  if (i === retries) throw err;
161
- console.warn(`[Dashboard] Connection failed (${err.message}). Retrying... (${i + 1}/${retries})`);
162
- // Use exponential backoff instead of endpoint rotation
 
 
163
  const delayMs = Math.min(1000 * Math.pow(1.5, i), 10000);
164
  await new Promise(r => setTimeout(r, delayMs));
165
  }
@@ -178,6 +200,7 @@ async function handleOAuthCallback(req, res) {
178
  }
179
 
180
  try {
 
181
  // Exchange code for token
182
  const tokenRes = await fetchWithRetry('https://discord.com/api/oauth2/token', {
183
  method: 'POST',
@@ -190,18 +213,26 @@ async function handleOAuthCallback(req, res) {
190
  redirect_uri: getRedirectUri()
191
  })
192
  });
 
193
  const tokenData = await tokenRes.json();
194
- if (!tokenData.access_token) return res.redirect('/?error=token_failed');
 
 
 
195
 
 
196
  // Fetch user profile
197
  const userRes = await fetchWithRetry('https://discord.com/api/users/@me', {
198
  headers: { Authorization: `Bearer ${tokenData.access_token}` }
199
  });
200
  const user = await userRes.json();
201
- if (!user.id) return res.redirect('/?error=user_failed');
 
 
 
202
 
203
  // Fetch user guilds
204
- console.log(`[Dashboard] Fetching guilds for user ${user.username}...`);
205
  const guildsRes = await fetchWithRetry('https://discord.com/api/users/@me/guilds', {
206
  headers: { Authorization: `Bearer ${tokenData.access_token}` }
207
  });
 
78
  function getRedirectUri() {
79
  if (REDIRECT_URI) return REDIRECT_URI;
80
  const spaceId = process.env.SPACE_ID;
81
+ if (spaceId) {
82
+ // If SPACE_ID is user/name, it becomes user-name.hf.space
83
+ const host = spaceId.includes('/') ? spaceId.replace('/', '-').toLowerCase() : spaceId.toLowerCase();
84
+ return `https://${host}.hf.space/callback`;
85
+ }
86
  return `http://localhost:${port}/callback`;
87
  }
88
 
 
118
 
119
  // --- Static Assets ---
120
  app.get('/', (req, res) => {
121
+ // If we get an OAuth code on the root route, redirect it to the callback handler
122
+ if (req.query.code) {
123
+ console.log("[Dashboard] Received OAuth code on root route, redirecting to /callback...");
124
+ return handleOAuthCallback(req, res);
125
+ }
126
  res.sendFile(path.join(__dirname, 'dashboard.html'));
127
  });
128
  app.get('/logo.png', (req, res) => {
 
154
 
155
  async function fetchWithRetry(url, options, retries = 2) {
156
  for (let i = 0; i <= retries; i++) {
157
+ const controller = new AbortController();
158
+ const timeoutId = setTimeout(() => controller.abort(), 20000); // 20s timeout per attempt
159
+
160
  try {
161
  let targetUrl = url;
 
162
  if (url.includes('discord.com/api')) {
 
163
  if (i > 0) console.log(`[Dashboard] Retrying Discord API call (${i + 1}/${retries})...`);
164
  }
165
 
166
+ const res = await fetch(targetUrl, {
167
+ ...options,
168
+ signal: controller.signal
169
+ });
170
+ clearTimeout(timeoutId);
171
+
172
+ if (!res.ok && i < retries) {
173
+ const text = await res.text().catch(() => '');
174
+ console.warn(`[Dashboard] API returned ${res.status}: ${text.substring(0, 100)}`);
175
+ throw new Error(`HTTP ${res.status}`);
176
+ }
177
  return res;
178
  } catch (err) {
179
+ clearTimeout(timeoutId);
180
  if (i === retries) throw err;
181
+
182
+ const isTimeout = err.name === 'AbortError';
183
+ console.warn(`[Dashboard] Attempt ${i + 1} failed (${isTimeout ? 'Timeout' : err.message}). Retrying...`);
184
+
185
  const delayMs = Math.min(1000 * Math.pow(1.5, i), 10000);
186
  await new Promise(r => setTimeout(r, delayMs));
187
  }
 
200
  }
201
 
202
  try {
203
+ console.log(`[Dashboard] Exchanging code for token... (Redirect URI: ${getRedirectUri()})`);
204
  // Exchange code for token
205
  const tokenRes = await fetchWithRetry('https://discord.com/api/oauth2/token', {
206
  method: 'POST',
 
213
  redirect_uri: getRedirectUri()
214
  })
215
  });
216
+
217
  const tokenData = await tokenRes.json();
218
+ if (!tokenData.access_token) {
219
+ console.error('[Dashboard] Token exchange failed:', tokenData);
220
+ return res.redirect('/?error=token_failed');
221
+ }
222
 
223
+ console.log(`[Dashboard] Token received. Fetching user profile...`);
224
  // Fetch user profile
225
  const userRes = await fetchWithRetry('https://discord.com/api/users/@me', {
226
  headers: { Authorization: `Bearer ${tokenData.access_token}` }
227
  });
228
  const user = await userRes.json();
229
+ if (!user.id) {
230
+ console.error('[Dashboard] Failed to fetch user profile:', user);
231
+ return res.redirect('/?error=user_failed');
232
+ }
233
 
234
  // Fetch user guilds
235
+ console.log(`[Dashboard] Fetching guilds for user ${user.username} (${user.id})...`);
236
  const guildsRes = await fetchWithRetry('https://discord.com/api/users/@me/guilds', {
237
  headers: { Authorization: `Bearer ${tokenData.access_token}` }
238
  });