shuarya2011 commited on
Commit
7dd4a60
·
verified ·
1 Parent(s): e2ea608

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +17 -235
app.js CHANGED
@@ -2,8 +2,6 @@ const express = require('express');
2
  const cors = require('cors');
3
  const fetch = require('node-fetch');
4
  const bodyParser = require('body-parser');
5
- const path = require('path');
6
- const fs = require('fs');
7
 
8
  const app = express();
9
  const PORT = 7860;
@@ -27,28 +25,15 @@ const STORAGE_POOLS = [
27
  const DB_FILE = "db.json";
28
 
29
  // --- MIDDLEWARE ---
30
- // ✅ IMPROVED CORS Configuration
31
- const corsOptions = {
32
- origin: '*',
33
- credentials: false,
34
- methods: ['GET', 'POST', 'OPTIONS'],
35
- allowedHeaders: ['Content-Type', 'Authorization'],
36
- optionsSuccessStatus: 200
37
- };
38
-
39
- app.use(cors(corsOptions));
40
- app.options('*', cors(corsOptions));
41
  app.use(bodyParser.json({ limit: '50mb' }));
42
  app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
43
 
44
- // Serve static files (for the tester)
45
- app.use(express.static('public'));
46
-
47
  // --- ROUTES ---
48
 
49
- // HOME PAGE WITH TESTER
50
  app.get('/', (req, res) => {
51
- res.sendFile(path.join(__dirname, 'public', 'tester.html'));
52
  });
53
 
54
  // HEALTH CHECK
@@ -57,182 +42,15 @@ app.get('/health', (req, res) => {
57
  res.json({
58
  status: 'ok',
59
  timestamp: new Date().toISOString(),
60
- pools: STORAGE_POOLS.length,
61
- tokensConfigured: configuredTokens,
62
- message: configuredTokens === 3 ? '✅ All tokens configured' : `⚠️ ${3 - configuredTokens} token(s) missing`
63
  });
64
  });
65
 
66
- // DASHBOARD ENDPOINT
67
- app.get('/dashboard', (req, res) => {
68
- res.send(`
69
- <!DOCTYPE html>
70
- <html>
71
- <head>
72
- <title>Insta API Dashboard</title>
73
- <style>
74
- body {
75
- font-family: Arial, sans-serif;
76
- margin: 0;
77
- padding: 20px;
78
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
79
- min-height: 100vh;
80
- }
81
- .container {
82
- max-width: 800px;
83
- margin: 0 auto;
84
- background: white;
85
- padding: 30px;
86
- border-radius: 10px;
87
- box-shadow: 0 10px 30px rgba(0,0,0,0.2);
88
- }
89
- h1 {
90
- color: #667eea;
91
- text-align: center;
92
- }
93
- .status-grid {
94
- display: grid;
95
- grid-template-columns: 1fr 1fr 1fr;
96
- gap: 20px;
97
- margin: 20px 0;
98
- }
99
- .status-card {
100
- background: #f8f9fa;
101
- padding: 20px;
102
- border-radius: 8px;
103
- border-left: 4px solid #667eea;
104
- text-align: center;
105
- }
106
- .status-card h3 {
107
- margin: 0;
108
- color: #333;
109
- font-size: 0.9em;
110
- }
111
- .status-badge {
112
- display: inline-block;
113
- margin-top: 10px;
114
- padding: 5px 10px;
115
- border-radius: 20px;
116
- font-weight: bold;
117
- font-size: 0.85em;
118
- }
119
- .status-badge.ok {
120
- background: #d4edda;
121
- color: #155724;
122
- }
123
- .status-badge.error {
124
- background: #f8d7da;
125
- color: #721c24;
126
- }
127
- .info-section {
128
- background: #e9ecef;
129
- padding: 15px;
130
- border-radius: 8px;
131
- margin: 20px 0;
132
- }
133
- .info-section h3 {
134
- margin-top: 0;
135
- }
136
- .endpoints {
137
- background: #f8f9fa;
138
- padding: 15px;
139
- border-radius: 8px;
140
- font-family: monospace;
141
- font-size: 0.9em;
142
- }
143
- .endpoints p {
144
- margin: 8px 0;
145
- }
146
- button {
147
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
148
- color: white;
149
- border: none;
150
- padding: 10px 20px;
151
- border-radius: 5px;
152
- cursor: pointer;
153
- margin: 5px;
154
- font-weight: bold;
155
- }
156
- button:hover {
157
- opacity: 0.9;
158
- }
159
- .button-group {
160
- text-align: center;
161
- margin: 20px 0;
162
- }
163
- </style>
164
- </head>
165
- <body>
166
- <div class="container">
167
- <h1>🚀 Insta API Dashboard</h1>
168
-
169
- <div class="status-grid">
170
- <div class="status-card">
171
- <h3>Server Status</h3>
172
- <div class="status-badge ok">✅ Online</div>
173
- </div>
174
- <div class="status-card">
175
- <h3>Storage Pools</h3>
176
- <div class="status-badge ok">3 Connected</div>
177
- </div>
178
- <div class="status-card">
179
- <h3>API Version</h3>
180
- <div class="status-badge ok">v1.0</div>
181
- </div>
182
- </div>
183
-
184
- <div class="info-section">
185
- <h3>📌 Storage Pools</h3>
186
- <p>✅ <strong>abhy60098/MY-STORAGE</strong></p>
187
- <p>✅ <strong>sushmasinharnc/MY-STORAGE</strong></p>
188
- <p>✅ <strong>shuarya2011/MY-STORAGE</strong></p>
189
- </div>
190
-
191
- <div class="info-section">
192
- <h3>📡 API Endpoints</h3>
193
- <div class="endpoints">
194
- <p><strong>GET /posts</strong> - Fetch all posts from all pools</p>
195
- <p><strong>POST /posts</strong> - Upload a new post</p>
196
- <p><strong>GET /health</strong> - Health check</p>
197
- <p><strong>GET /</strong> - Interactive API Tester</p>
198
- </div>
199
- </div>
200
-
201
- <div class="info-section">
202
- <h3>📝 POST Request Example</h3>
203
- <div class="endpoints">
204
- <p>curl -X POST http://localhost:7860/posts \\</p>
205
- <p style="margin-left: 20px;">-H "Content-Type: application/json" \\</p>
206
- <p style="margin-left: 20px;">-d '{</p>
207
- <p style="margin-left: 40px;">"username": "john_doe",</p>
208
- <p style="margin-left: 40px;">"caption": "My awesome post!",</p>
209
- <p style="margin-left: 40px;">"imageBase64": "iVBORw0KGgo...",</p>
210
- <p style="margin-left: 40px;">"fileName": "photo.jpg"</p>
211
- <p style="margin-left: 20px;">}'</p>
212
- </div>
213
- </div>
214
-
215
- <div class="button-group">
216
- <button onclick="window.location.href='/'">📤 Go to Tester</button>
217
- <button onclick="fetch('/health').then(r => r.json()).then(d => alert(JSON.stringify(d, null, 2)))">🏥 Check Health</button>
218
- <button onclick="window.location.reload()">🔄 Refresh</button>
219
- </div>
220
- </div>
221
- </body>
222
- </html>
223
- `);
224
- });
225
-
226
  // GET: Fetch posts from all pools
227
  app.get('/posts', async (req, res) => {
228
  try {
229
- console.log('\n📥 GET /posts - Fetching from all pools...');
230
-
231
  const allResults = await Promise.all(STORAGE_POOLS.map(async (pool) => {
232
- if (!pool.token) {
233
- console.warn(`⚠️ Token missing for ${pool.repo}`);
234
- return [];
235
- }
236
 
237
  const url = `https://huggingface.co/api/datasets/${pool.repo}/raw/main/${DB_FILE}`;
238
  try {
@@ -242,24 +60,18 @@ app.get('/posts', async (req, res) => {
242
 
243
  if (response.ok) {
244
  const data = await response.json();
245
- console.log(`✅ Fetched ${(data.posts || []).length} posts from ${pool.repo}`);
246
  return data.posts || [];
247
  }
248
- console.log(`ℹ️ File not found in ${pool.repo}`);
249
  return [];
250
  } catch (err) {
251
- console.error(`❌ Error fetching from ${pool.repo}:`, err.message);
252
  return [];
253
  }
254
  }));
255
 
256
  const mergedPosts = allResults.flat().sort((a, b) => b.id - a.id);
257
- console.log(`📊 Total posts merged: ${mergedPosts.length}\n`);
258
-
259
  res.json(mergedPosts);
260
  } catch (err) {
261
- console.error("GET Error:", err);
262
- res.status(500).json({ error: "Failed to fetch posts from pools." });
263
  }
264
  });
265
 
@@ -269,26 +81,20 @@ app.post('/posts', async (req, res) => {
269
  const { username, caption, imageBase64, fileName } = req.body;
270
 
271
  if (!imageBase64 || !username) {
272
- return res.status(400).json({ error: "Missing required fields (username or image)." });
273
  }
274
 
275
- // Pick random pool
276
  const pool = STORAGE_POOLS[Math.floor(Math.random() * STORAGE_POOLS.length)];
277
 
278
  if (!pool.token) {
279
- return res.status(500).json({ error: "Storage pool token not configured in Secrets." });
280
  }
281
 
282
  const timestamp = Date.now();
283
  const imagePath = `uploads/${timestamp}-${fileName}`;
284
-
285
- console.log(`\n📤 POST /posts - Uploading to ${pool.repo}`);
286
-
287
  const imageBuffer = Buffer.from(imageBase64, 'base64');
288
 
289
- // Step 1: Upload image
290
- console.log(`🖼️ Uploading image: ${imagePath}`);
291
-
292
  const uploadImageUrl = `https://huggingface.co/api/datasets/${pool.repo}/commit/main`;
293
  const imageUploadRes = await fetch(uploadImageUrl, {
294
  method: 'POST',
@@ -304,21 +110,18 @@ app.post('/posts', async (req, res) => {
304
  content: imageBuffer.toString('base64')
305
  }
306
  ],
307
- commit_message: `Upload image from ${username}`
308
  })
309
  });
310
 
311
  if (!imageUploadRes.ok) {
312
  const errorText = await imageUploadRes.text();
313
- console.error("❌ Image upload failed:", errorText);
314
  throw new Error(`Image Upload Failed: ${errorText}`);
315
  }
316
 
317
- console.log("✅ Image uploaded successfully");
318
-
319
  const finalImageUrl = `https://huggingface.co/datasets/${pool.repo}/resolve/main/${imagePath}`;
320
 
321
- // Step 2: Fetch existing db.json
322
  const dbUrl = `https://huggingface.co/api/datasets/${pool.repo}/raw/main/${DB_FILE}`;
323
  const dbRes = await fetch(dbUrl, {
324
  headers: { Authorization: `Bearer ${pool.token}` }
@@ -329,7 +132,7 @@ app.post('/posts', async (req, res) => {
329
  db = await dbRes.json();
330
  }
331
 
332
- // Step 3: Add new post
333
  db.posts.unshift({
334
  id: timestamp,
335
  username,
@@ -338,9 +141,7 @@ app.post('/posts', async (req, res) => {
338
  pool: pool.repo
339
  });
340
 
341
- // Step 4: Update db.json
342
- console.log(`💾 Updating database...`);
343
-
344
  const updateDbUrl = `https://huggingface.co/api/datasets/${pool.repo}/commit/main`;
345
  const dbUploadRes = await fetch(updateDbUrl, {
346
  method: 'POST',
@@ -356,40 +157,21 @@ app.post('/posts', async (req, res) => {
356
  content: Buffer.from(JSON.stringify(db, null, 2)).toString('base64')
357
  }
358
  ],
359
- commit_message: "Update database with new post"
360
  })
361
  });
362
 
363
  if (!dbUploadRes.ok) {
364
- const errorText = await dbUploadRes.text();
365
- console.error("❌ Database update failed:", errorText);
366
- throw new Error(`Database update failed: ${errorText}`);
367
  }
368
 
369
- console.log("✅ Database updated successfully\n");
370
  res.status(201).json({ success: true, imageUrl: finalImageUrl });
371
 
372
  } catch (err) {
373
- console.error("POST Error:", err);
374
  res.status(500).json({ error: err.message });
375
  }
376
  });
377
 
378
- // ERROR HANDLING
379
- app.use((err, req, res, next) => {
380
- console.error('Server Error:', err);
381
- res.status(500).json({ error: 'Internal server error' });
382
- });
383
-
384
- // Start server
385
  app.listen(PORT, () => {
386
- console.log(`\n${'='.repeat(60)}`);
387
- console.log(`✅ Insta API Server Running`);
388
- console.log(`${'='.repeat(60)}`);
389
- console.log(`🌐 Server URL: http://localhost:${PORT}`);
390
- console.log(`📊 Dashboard: http://localhost:${PORT}/dashboard`);
391
- console.log(`🧪 Tester: http://localhost:${PORT}`);
392
- console.log(`${'='.repeat(60)}\n`);
393
- });
394
-
395
- module.exports = app;
 
2
  const cors = require('cors');
3
  const fetch = require('node-fetch');
4
  const bodyParser = require('body-parser');
 
 
5
 
6
  const app = express();
7
  const PORT = 7860;
 
25
  const DB_FILE = "db.json";
26
 
27
  // --- MIDDLEWARE ---
28
+ app.use(cors());
 
 
 
 
 
 
 
 
 
 
29
  app.use(bodyParser.json({ limit: '50mb' }));
30
  app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
31
 
 
 
 
32
  // --- ROUTES ---
33
 
34
+ // HOME - Serve Tester HTML
35
  app.get('/', (req, res) => {
36
+ res.sendFile(__dirname + '/tester.html');
37
  });
38
 
39
  // HEALTH CHECK
 
42
  res.json({
43
  status: 'ok',
44
  timestamp: new Date().toISOString(),
45
+ tokensConfigured: configuredTokens
 
 
46
  });
47
  });
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  // GET: Fetch posts from all pools
50
  app.get('/posts', async (req, res) => {
51
  try {
 
 
52
  const allResults = await Promise.all(STORAGE_POOLS.map(async (pool) => {
53
+ if (!pool.token) return [];
 
 
 
54
 
55
  const url = `https://huggingface.co/api/datasets/${pool.repo}/raw/main/${DB_FILE}`;
56
  try {
 
60
 
61
  if (response.ok) {
62
  const data = await response.json();
 
63
  return data.posts || [];
64
  }
 
65
  return [];
66
  } catch (err) {
 
67
  return [];
68
  }
69
  }));
70
 
71
  const mergedPosts = allResults.flat().sort((a, b) => b.id - a.id);
 
 
72
  res.json(mergedPosts);
73
  } catch (err) {
74
+ res.status(500).json({ error: "Failed to fetch posts." });
 
75
  }
76
  });
77
 
 
81
  const { username, caption, imageBase64, fileName } = req.body;
82
 
83
  if (!imageBase64 || !username) {
84
+ return res.status(400).json({ error: "Missing username or image." });
85
  }
86
 
 
87
  const pool = STORAGE_POOLS[Math.floor(Math.random() * STORAGE_POOLS.length)];
88
 
89
  if (!pool.token) {
90
+ return res.status(500).json({ error: "Storage pool token not configured." });
91
  }
92
 
93
  const timestamp = Date.now();
94
  const imagePath = `uploads/${timestamp}-${fileName}`;
 
 
 
95
  const imageBuffer = Buffer.from(imageBase64, 'base64');
96
 
97
+ // Upload image
 
 
98
  const uploadImageUrl = `https://huggingface.co/api/datasets/${pool.repo}/commit/main`;
99
  const imageUploadRes = await fetch(uploadImageUrl, {
100
  method: 'POST',
 
110
  content: imageBuffer.toString('base64')
111
  }
112
  ],
113
+ commit_message: `Upload from ${username}`
114
  })
115
  });
116
 
117
  if (!imageUploadRes.ok) {
118
  const errorText = await imageUploadRes.text();
 
119
  throw new Error(`Image Upload Failed: ${errorText}`);
120
  }
121
 
 
 
122
  const finalImageUrl = `https://huggingface.co/datasets/${pool.repo}/resolve/main/${imagePath}`;
123
 
124
+ // Fetch existing db.json
125
  const dbUrl = `https://huggingface.co/api/datasets/${pool.repo}/raw/main/${DB_FILE}`;
126
  const dbRes = await fetch(dbUrl, {
127
  headers: { Authorization: `Bearer ${pool.token}` }
 
132
  db = await dbRes.json();
133
  }
134
 
135
+ // Add new post
136
  db.posts.unshift({
137
  id: timestamp,
138
  username,
 
141
  pool: pool.repo
142
  });
143
 
144
+ // Update db.json
 
 
145
  const updateDbUrl = `https://huggingface.co/api/datasets/${pool.repo}/commit/main`;
146
  const dbUploadRes = await fetch(updateDbUrl, {
147
  method: 'POST',
 
157
  content: Buffer.from(JSON.stringify(db, null, 2)).toString('base64')
158
  }
159
  ],
160
+ commit_message: "Update database"
161
  })
162
  });
163
 
164
  if (!dbUploadRes.ok) {
165
+ throw new Error("Database update failed.");
 
 
166
  }
167
 
 
168
  res.status(201).json({ success: true, imageUrl: finalImageUrl });
169
 
170
  } catch (err) {
 
171
  res.status(500).json({ error: err.message });
172
  }
173
  });
174
 
 
 
 
 
 
 
 
175
  app.listen(PORT, () => {
176
+ console.log(`\n✅ Insta API Server Running on http://localhost:${PORT}\n`);
177
+ });